Inigo
Inigo

Reputation: 8685

Javascript: Setting variables in function declaration

I have the following javascript code:

    function toggleHiddenOps(dir, tour = false){
        // do stuff
    }

I noticed it was breaking in Chrome and IE (seems to work in FF 27). If I change the above to:

    function toggleHiddenOps(dir, tour){
        // do stuff
    }

It resolves the problem. Is there some issue with declaring variables like this in JS? Or perhaps my problem actually lies elsewhere?

Thanks.

Upvotes: 0

Views: 53

Answers (4)

edi9999
edi9999

Reputation: 20544

This functionality exists only in FF for now. It will be in ECMAScript6, so expect it to start showing up in other engines over time.

Chrome, IE, Opera and Safari don't support that syntax in their latest versions.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/default_parameters?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2Fdefault_parameters

A good workaround for this is to use arg= typeof arg !== 'undefined' ? arg : defaultValue;

For example:

function multiply(a, b) {
   b = typeof b !== 'undefined' ?  b : 1;
   return a*b;
}

multiply(5); // 5

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/default_parameters

Upvotes: 1

Marat Tanalin
Marat Tanalin

Reputation: 14123

You cannot specify default values in JS using PHP syntax.

To be fair, draft ECMAScript 6 specification allows to specify default argument value like in PHP, and this is even supported in Firefox 15+, but note that support of ES6 itself is mostly experimental and can theoretically be changed or removed at any point.

A future-proof/cross-browser way to check in JS if argument is not specified is following:

function toggleHiddenOps(dir, tour) {
    if ('undefined' === typeof tour) {
        tour = 'Some default value';
    }

    // do stuff
}

Upvotes: 0

defool
defool

Reputation: 301

Javascript function don't support default paramter, a hack for it is:

function toggleHiddenOps(dir, tour){
    tour = typeof tour === 'undefined' ? 'default value' : tour
    console.log(dir)
    console.log(tour)
}
toggleHiddenOps('dir')

Upvotes: 0

Andrew Templeton
Andrew Templeton

Reputation: 1696

This is illegal in javascript.

If you want a default exactly false:

function toggleHiddenOps(dir, tour){
   tour = tour === void(0) ? false : tour;
   // do stuff
}

If you only care if its falsey:

function toggleHiddenOps(dir, tour){
   // do stuff, tour equals undefined now if not passed 2nd param
}

Upvotes: 0

Related Questions