Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 977
ACs Avatar asked Mar 13 '17 16:03

ACs


3 Answers

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.

like image 108
Shilly Avatar answered Sep 28 '22 05:09

Shilly


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.

like image 29
rasmeister Avatar answered Sep 28 '22 03:09

rasmeister


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

like image 33
lena Avatar answered Sep 28 '22 03:09

lena