I saw something like this in Javascript :
function name (secret) {
secret = secret || {};
i can't find anywhere what exactly means secret = secret || {};
Is that mean create global variable with value of passed argument or an object?
When do you use it? When there is no argument passed?
If the variable secret
is falsy (one of the following):
false
0
''
(empty string)null
undefined
NaN
..then set it to {}
(an empty object - it's the same as new Object()
).
It could also be written as this:
if (!secret) secret = {};
But as it's longer most people prefer the above.
This solution is useful as javascript has no default function parameters.
For example an example in PHP could look like this:
<?php
function foo($bar = 'default') {
echo $bar;
}
?>
and in JS that could be
function foo(bar) {
bar = bar || 'default';
console.log(bar);
}
foo(); //default
foo(NaN); //default
foo(undefined); //default
foo(null); //default
foo(false); //default
foo(0); //default
foo(''); //default
foo('something'); //something
foo(12); //12
foo(1.2); //1.2
If you only want to check for no value (no falsy values), then you can use the typeof
function in JS:
function foo(bar) {
if (typeof bar == 'undefined') bar = 'default';
console.log(bar);
}
foo(); //default
foo(undefined); //default
foo(NaN); //NaN
foo(null); //null
foo(false); //false
foo(0); //0
foo(''); //(empty string)
foo('something'); //something
foo(12); //12
foo(1.2); //1.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With