Grateful February 2016

Default Parameters in Function Expressions

Default parameters in javscript function declerations can be achieved with a simple assignment as follows:

function foo(arg1 = 'default1', arg2 = 'default2') { ... }

But how can I have default parameters for function expressions, as the following does NOT work in chrome v47:

var foo = function (arg1 = 'default1', arg2 = 'default2') { ... }

Any pointers would be helpful.

Answers


Gavriel February 2016

You can't do this in javascript:

function foo(arg1 = 'default1', arg2 = 'default2') { ; }

See in your console, it gives syntax error. You can do this:

function foo(arg1, arg2) {
   if ("undefined" == typeof arg2) {
       arg2 = "default2";
   }
}

var foo2 = function(arg1, arg2) {
   if ("undefined" == typeof arg2) {
       arg2 = "default2";
   }
}

Post Status

Asked in February 2016
Viewed 3,237 times
Voted 6
Answered 1 times

Search




Leave an answer