Proper way to define default values for function arguments in JavaScript

10,052

Solution 1

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.

Solution 2

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.

Solution 3

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

Share:
10,052
ACs
Author by

ACs

Updated on June 16, 2022

Comments

  • ACs
    ACs almost 2 years

    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.