What it means
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()
).
Alternative code
It could also be written as this:
if (!secret) secret = {};
But as it's longer most people prefer the above.
Why?
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
What if I only want to set a default if nothing else has been set?
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