JS
See the Pen thecodelog.com - ES6 Default Arguments 1 by Deano (@deangilewicz) on CodePen.
If we want to assume a default value then previously we may have set it up like this.
See the Pen thecodelog.com - ES6 Default Arguments 2 by Deano (@deangilewicz) on CodePen.
but with ES6 we can make use of default arguments and set it up like this:
See the Pen thecodelog.com - ES6 Default Arguments 3 by Deano (@deangilewicz) on CodePen.
Care must be taken when passing a falsy value into an ES5 function declaration that makes use of setting a fallback value since the falsy value causes the function to return the fallback value. This could cause unexpected behavior when passing zero.
See the Pen thecodelog.com - ES6 Default Arguments 4 by Deano (@deangilewicz) on CodePen.
Falsy values are handled slightly differently when using ES6 default arguments. Be aware that null is coerced to 0 which is used as a value.
See the Pen thecodelog.com - ES6 Default Arguments 5 by Deano (@deangilewicz) on CodePen.
In es6 functions default value expressions can be used but be aware that they are lazily evaluated, which means they only run if a parameter’s argument is omitted or is undefined:
See the Pen thecodelog.com - ES6 Default Arguments 6 by Deano (@deangilewicz) on CodePen.
One other note is that formal parameters in a function declaration are in their own scope.
See the Pen thecodelog.com - ES6 Default Arguments 7 by Deano (@deangilewicz) on CodePen.
The w in the w + 1 default value expression looks for w in the formal parameters’ scope, but does not find it, so the outer scope’s w is used. Next, the x in the x + 1 default value expression finds x in the formal parameters’ scope, and luckily x has already been initialized, so the assignment to y works fine. However, the z in z + 1 finds z as not yet initialized at that moment so it never tries to find the z from the outer scope.