Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding default values within javascript custom function

mmorning, im a php man so I cant understand why this is throwing an error:

function display_message( bool, msg, remove_wrap = false ) {
    if( bool === true ) {
        error = get_msg( msg, remove_wrap );
    }else{
        error = get_error_msg( msg, remove_wrap );
    }
    $.fancybox( error, { 'autoDimensions' : false, 'width' : 450, 'height' : 'auto', 'transitionIn' : 'none', 'transitionOut' : 'none' });
}

the culprit being 'remove_wrap = false' from the function.

can anyone tell me what i should be writing here. regards, phil

like image 662
Phil Jackson Avatar asked Dec 12 '22 16:12

Phil Jackson


1 Answers

JavaScript doesn't support argument defaults like that. Like many other have said, you can pick a default inside your function. A concise idiom for setting a default value is:

arg = arg || default;

So, in your case it would be:

remove_wrap = remove_wrap || false;

However, if your default value is false, you don't even need to set it. Because, when that argument is lacking, its value will be of type undefined inside the function and that value is already "falsy": you can directly use remove_wrap as it is:

function display_message(bool, msg, remove_wrap) {
    var error = bool
        ? get_msg(msg, remove_wrap)
        : get_error_msg(msg, remove_wrap);

    $.fancybox(error, {
        autoDimensions: false,
        width: 450,
        height: "auto",
        transitionIn: "none",
        transitionOut: "none"
    });
}

Bonus: Note that I've also added a var to the error variable (don't omit the var unless your true intention is to create a global variable). I've also shortened the assignment with a ternary expression. I've also reformatted the fancybox call with a syntax that most people find more readable.

like image 64
Ates Goral Avatar answered Jan 09 '23 22:01

Ates Goral