90

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")
{
    // ...
}
doppelgreener
  • 5,471
  • 9
  • 47
  • 62
Royal Pinto
  • 2,739
  • 6
  • 25
  • 39

3 Answers3

157

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"; 
  }
.
.
.
mplungjan
  • 155,085
  • 27
  • 166
  • 222
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")
{
  // ...
}
sfletche
  • 42,426
  • 25
  • 94
  • 115
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
}
zVictor
  • 3,418
  • 3
  • 38
  • 52