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

I created a function like this:

function saveItem(andClose = false) {

}

It works fine in Firefox

In IE it gives this error on the console: Expected ')'

In Chrome it gives this error in the console: Uncaught SyntaxError: Unexpected token =

Both browsers mark the source of the error as the function creation line.

Answers:

Answer

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') {}
Answer

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.

Answer

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
    }
}
Answer

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:

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.

Answer

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

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.