What does “var FOO = FOO || {}” (assign a variable or an empty object to that variable) mean in Javascript?

前端 未结 7 1948
野性不改
野性不改 2020-11-22 02:07

Looking at an online source code I came across this at the top of several source files.

var FOO = FOO || {};
FOO.Bar = …;

But I have no ide

相关标签:
7条回答
  • 2020-11-22 03:01

    Another common use for || is to set a default value for an undefined function parameter also:

    function display(a) {
      a = a || 'default'; // here we set the default value of a to be 'default'
      console.log(a);
    }
    
    // we call display without providing a parameter
    display(); // this will log 'default'
    display('test'); // this will log 'test' to the console
    

    The equivalent in other programming usually is:

    function display(a = 'default') {
      // ...
    }
    
    0 讨论(0)
提交回复
热议问题