93

I am writing a Javascript function with an optional argument, and I want to assign the optional argument a default value. How can I assign it a default value?

I thought it would be this, but it doesn't work:

function(nodeBox,str = "hai")
{
    // ...
}
3
  • 4
    This now works in ES6 Commented Oct 12, 2015 at 23:52
  • Yeah got to know about this recently. es6-features.org/#DefaultParameterValues Commented Oct 13, 2015 at 4:40
  • I would however try and keep the logic in the parameters to a minimum..... Commented Oct 13, 2015 at 6:29

3 Answers 3

158

If str is null, undefined or 0, this code will set it to "hai"

function(nodeBox, str) {
  str = str || "hai";
.
.
.

If you also need to pass 0, you can use:

function(nodeBox, str) {
  if (typeof str === "undefined" || str === null) { 
    str = "hai"; 
  }
.
.
.
Sign up to request clarification or add additional context in comments.

4 Comments

@Roayl: This will also work for false if that is what you mean.
No default should be true. I mean if i will not pass parametr, it should take true
OK i will take default as false only. No need set to false. Default it will take as false.
It would be counter intuitive to have a variable you do NOT pass end up as true.
32

ES6 Update - ES6 (ES2015 specification) allows for default parameters

The following will work just fine in an ES6 (ES015) environment...

function(nodeBox, str="hai")
{
  // ...
}

Comments

5

You can also do this with ArgueJS:

function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

  // and now on, you can access your arguments by
  //   arguments.nodebox and arguments.str
}

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.