简体   繁体   中英

Proper way to define default values for function arguments in JavaScript

Since years from when I first met JavaScript I always used default values for function arguments, like:

function addToCartCallback3(responseData, toCartBtn = null) {
    // ...
}

But I noticed that now my PhpStorm warns me that this is wrong, and after toCartBtn comma , or closing parenthesis ) is expected.

The code above works fine in Chrome and Firefox but kills all the JavaScript in IE11. (In IE11 the console tells me the same as PhpStorm)

Why is this code wrong, or what should I use?

I know that (typeof toCartBtn == 'undefined') should do the trick, but I'm really curious why is the other method all of a sudden considered syntactically wrong.

As written this only works in ES6 browsers, since ES6 will contain this syntax for defaults. So on IE11 you'll have to put the default inside the body:

function addToCartCallback3(responseData, toCartBtn) {
  toCartBtn = toCartBtn || 'defaultHere';
}

Do note that if you're default is supposed to be null, you can just not use a default, since in most cases, an undefined argument will behave the same way as a argument with value null.

IE11 does not support default parameters. This is an extension in ES6 in the JavaScript language that browser does not recognize.

You can see this by having a look at this useful resource . If you look at 'default function parameters' you will see it is not supported in that version of IE.

To get this syntax accepted by PHPStorm, please make sure to set JavaScript language Version to ECMAScript 6 in File | Settings | Languages & Frameworks | JavaScript File | Settings | Languages & Frameworks | JavaScript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM