Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function variable preset

I have a function that I want to pass an argument to, however I want it to default to 0.

Is it possible todo it similarly to PHP, like:

function byMonth(export=0) {

Many thanks

like image 798
azz0r Avatar asked Sep 03 '10 17:09

azz0r


People also ask

What is default value of VAR in JavaScript?

Setting JavaScript default parameters for a function In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined .

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.

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

From ES6/ES2015, default parameters are in the language specification. just works. 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 JavaScript function accept parameters?

A JavaScript function does not perform any checking on parameter values (arguments).


1 Answers

Dont do this

function byMonth(export){
  export = export || 0;
  alert(export);
}

Edit:

The previous version has a silent bug, I'm leaving it just as an example of what NOT TO DO.

The problem is, suppose you pass the function the argument false, it will take the default value although you actually called it with an argument.

All this other parameters will be ignored and the default will be used (because of javascript concept of falsy)

  • The number zero 0
  • An empty string ""
  • NaN
  • false
  • null
  • and (obviously) undefined

A safer way to check for the presence of the parameter is:

  function byMonth(export){
      if(export === undefined) export = 0;
  }

Edit 2:

The previous function is not 100% secure since someone (an idiot probably) could define undefined making the function to behave unexpectedly. This is a final, works-anywhere, bulletproof version:

function byMonth(export){
  var undefined;
  if(export === undefined) export = 0;
}
like image 164
Pablo Fernandez Avatar answered Sep 22 '22 03:09

Pablo Fernandez