Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Functions and default parameters, not working in IE and Chrome

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.

like image 357
Talon Avatar asked Mar 02 '13 19:03

Talon


People also ask

Does IE support default parameter values?

The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ).

Can I use default parameters JavaScript?

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 .


2 Answers

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') {} 
like image 136
juco Avatar answered Oct 01 '22 22:10

juco


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.

like image 23
the system Avatar answered Oct 01 '22 23:10

the system