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?
What it means
If the variable
secretis falsy (one of the following):false0''(empty string)nullundefinedNaN..then set it to
{}(an empty object – it’s the same asnew Object()).Alternative code
It could also be written as this:
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:
and in JS that could be
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
typeoffunction in JS: