I created a function like this:
function saveItem(andClose = false) { }
It works fine in Firefox
In IE it gives this error on the console: Expected ')'
In Chrome it gives this error in the console: Uncaught SyntaxError: Unexpected token =
Both browsers mark the source of the error as the function creation line.
The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ).
In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined .
You can't do this, but you can instead do something like:
function saveItem(andClose) { if(andClose === undefined) { andClose = false; } }
This is often shortened to something like:
function setName(name) { name = name || 'Bob'; }
Update
The above is true for ECMAScript <= 5. ES6 has proposed Default parameters. So the above could instead read:
function setName(name = 'Bob') {}
That's not a valid ECMAScript syntax, but it is a valid syntax for Mozilla's superset of features they add to their implementation of the language.
Default parameter assignment syntax is likely coming in ECMAScript 6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With