Predefined options

I want to be able to do this in JavaScript:

function myFunction(one, two = 1) { // code } myFunction("foo", "2"); myFunction("bar"); 

I tried this and it does not work. I do not know what to call this type of parameter, can someone point me in the right direction?

Thanks.

+4
source share
4 answers
 function foo(a, b) { a = typeof a !== 'undefined' ? a : 42; b = typeof b !== 'undefined' ? b : 'default_b'; //... } 

Possible duplicate Set default parameter value for JavaScript function

+2
source
 function myFunction(one, two) { two = two || 1 } 

To be more precise, for example, it may not work when two are zero, check for null or undefined, for example.

 if (typeof two === "undefined") two = 1 
+2
source

Use this:

 function myFunction(one, two) { if (typeof two == 'undefined') two = 1; ... } 

Beware of making a common mistake

 two = two || 1; 

because it will not allow you to provide a "" or 0 .

+2
source

Try:

 if ( typeof two === "undefined" ) two = 2; 

or

 two = typeof two !== "undefined" ? two : 2; 

Undefined arguments will be undefined , which is a "fake" value. We can check this falsity and change the value accordingly.

0
source

Source: https://habr.com/ru/post/1442623/


All Articles