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.
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
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
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 .
""
0
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.
undefined
Source: https://habr.com/ru/post/1442623/More articles:Integrating Google Analytics Tracking into IOS App - iosSublime Text don't build anything - build"Xaml Parsing Failed" in Windows Store User Management - c #Using re.MULTILINE and re.DOTALL together python - pythonThe python program received an X Window System error - pythonSoundCloud API iOS, no sharing - listening only - iosJavadoc formatting from upgrade to Java 7 - javaHow to create a web worker from a script from a subdomain? - javascriptNoir uberjar only works in the build directory - clojureHow to parse the following HTML in python beautifulsoup? - pythonAll Articles