Search code examples
javascriptminifydefault-valuebundling-and-minification

Minify javascript with default value issue


I have functions with a default value like this:

function f(a, b = 'something') {
    //do stuff
}

This works just fine, but if I try to minify my JS file using online related apps, an error occurs :

Error: Unexpected token operator '=', expected punc ','

As I know using = to set default value in Javascript is legal, so why do I receive this error?

Do i have to define a default value in the body of function?


Solution

  • Using = to set a default default values for function parameters in Javascript is an ES6 feature that is currently only supported by Chrome 49 and Firefox 15.0 :

    enter image description here

    Because of the limited browser support, few (if any) minifiers already support this feature.

    Alternative 1 :

    You could set default parameters like this :

    function f(a, b) {
        b = typeof b  === 'undefined' ? 'something' : b;
        //do stuff
    }
    

    Alternative 2 :

    You could use a transpiler like Babel to convert ES6 code to something that older browsers & minifiers understand.