How do I set the default value for an optional argument in Javascript? [duplicate]

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")
{
    // ...
}

Solution 1:

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"; 
  }
.
.
.

Solution 2:

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

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

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