Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of || {} in Javascript [duplicate]

Tags:

javascript

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?

like image 317
Teq1 Avatar asked Oct 22 '12 17:10

Teq1


1 Answers

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
like image 75
h2ooooooo Avatar answered Oct 07 '22 23:10

h2ooooooo