2

In PHP I can do something like this:

public myFunction($variable=0) {
    //Do some stuff
}

In Javascript, the following does not work:

var myFunction = function(variable=0 )
{

    //do some stuff...

};
HappyCoder
  • 5,285
  • 4
  • 36
  • 67

2 Answers2

4

Try this

var myFunction = function(variable) {
  variable = variable || 0;
  // this variant works for all falsy values "", false, null, undefined...
  // if you need check only undefiend, use this variant 
  // variable = typeof(variable) == 'undefined' ? 0 : variable
};

Default function parameters will be in ES6; ES5 does not allow it.

Oleksandr T.
  • 69,412
  • 16
  • 152
  • 136
1

With ECMAScript 6 you can do this.

Check an example:

function multiply(a, b = 1) {
  return a*b;
}

multiply(5); // 5

But this is still experimental and today is only supported by Mozilla Firefox browser.

Check this link do see documentantion:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters#Browser_compatibility

Leonardo Delfino
  • 1,441
  • 8
  • 19