Javascript Functions and default parameters, not working in IE and Chrome

You can't do this, but you can instead do something like:

function saveItem(andClose) {
   if(andClose === undefined) {
      andClose = false;
   }
}

This is often shortened to something like:

function setName(name) {
  name = name || 'Bob';
}

Update

The above is true for ECMAScript <= 5. ES6 has proposed Default parameters. So the above could instead read:

function setName(name = 'Bob') {}

That's not a valid ECMAScript syntax, but it is a valid syntax for Mozilla's superset of features they add to their implementation of the language.

Default parameter assignment syntax is likely coming in ECMAScript 6.


Javascript does not allow a "default" specifier.

A quick way of doing what you would want is changing:

function saveItem(andClose = false) {

}

to the following:

function saveItem(andClose) {
    // this line will check if the argument is undefined, null, or false
    // if so set it to false, otherwise set it to it's original value
    var andClose = andClose || false;

    // now you can safely use andClose
    if (andClose) {
        // do something
    }
}

The code you provided won't run in Chrome < version 49: https://kangax.github.io/compat-table/es6/#test-default_function_parameters

You used valid ECMAScript 2015 syntax:

  • MDN: Default Parameters.
  • ES2015 Spec: default value parameter initializers

In my opinion, the best way to use ES2015 features is to bundle assets with Browserify or WebPack, with a step for using Babel to trans-compile ES2015 to ES5. That way you don't have to worry about that ES2015 browser compatibility chart. It's a pain to get started the first time, but worth it.


In your case, you have an other alternative to be sure that your variable is a boolean:

function saveItem(andClose) {
  andClose = true == andClose;
  // ...
}

Default value is undefined, and true == undefined => false, so your default value will be false :)