Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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")
{
    // ...
}
like image 936
Royal Pinto Avatar asked Jul 16 '11 11:07

Royal Pinto


People also ask

How do you pass an optional argument in JavaScript?

To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator ('||'): In this approach, the optional parameter is Logically ORed with the default value within the body of the function. Note: The optional parameters should always come at the end on the parameter list.

How do you define a default value for a JavaScript function parameter?

In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined .

Which is the correct way to give default value to the parameter A in a function F?

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. function foo(a, b) { a = typeof a !==

Can you assign the default values to a function parameters?

Default parameter in JavascriptThe default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.


3 Answers

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"; 
  }
.
.
.
like image 106
mplungjan Avatar answered Oct 13 '22 06:10

mplungjan


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

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

function(nodeBox, str="hai")
{
  // ...
}
like image 35
sfletche Avatar answered Oct 13 '22 06:10

sfletche


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
}
like image 34
zVictor Avatar answered Oct 13 '22 05:10

zVictor