92

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
  • 4,809
  • 10
  • 46
  • 63
Royal Pinto
  • 2,869
  • 8
  • 27
  • 39

3 Answers3

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"; 
  }
.
.
.
mplungjan
  • 169,008
  • 28
  • 173
  • 236
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
  • 47,248
  • 30
  • 103
  • 119
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,610
  • 3
  • 41
  • 56