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...

};
0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This isn't exactly the same as the PHP code though. You want to use variable = typeof(variable) === 'undefined' ? 0 : variable.
@h2ooooooo thanks for your comment, I've added you variant also.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.