Pergunta

Possible Duplicate:
What does “var FOO = FOO || {}” mean in Javascript?
Javascript - Can you add condition to variable declaration

I believe this has to do with scoping, and not redefining scope. I see a lot of this in popular javascript frameworks:

var something = something || {};

Is that to do with not accidentally redefining a top-level variable?

Foi útil?

Solução

You are correct. If the variable already exists (ours or not), don't change it. If it doesn't exist, let's create a new one.

Outras dicas

var something = something || {};

can be used inside of functions with parameters that may not be set

    function doStuff( arg1, arg2, arg3 ) {
        arg2 = arg2 || {};
        arg3 = arg3 || arg1 + 2;
    };

this makes the second and third arguments optional when you call the function doStuff

This creates a new object with local scope. If the outer something is null, false, or undefined (or otherwise falsy), the new variable will be an empty object {}.

You're not redefining scope, you're simply ensuring that a variable exists within the existing scope. The assignment statement can be read as:

"If something exists (and is not undefined, null, 0 or false, set something = something (i.e., do nothing). If it doesn't exist, create it and set it equal to an empty object literal"

It's the same as doing:

var something = ( something ) ? something : {};

Where ( something ) is the evaluation of a truthy or falsy value. If truthy (something exists) it will equal itself, or otherwise an empty object.

This construct is pretty useful to not overwrite existing data. Let's assume we're dealing with multiple Javascript files and we want to share some data on some object.

a.js

var share = window.share = share || { };
share.thisIsA = true;

b.js

var share = window.share = share || { };
share.thisIsB = true;

If we have even more than two files and we load those files asyncronously (we can't guarantee order) we don't overwrite that global share object if it was defined and filled before. This is a very common practice for namespacing objects or config objects.

Another very common use case is for creating default values. For instance

function foo( option ) {
    option = option || 'something';

    if( option === 'foobar' ) {} // ...
}

There, we use the patter to have at least one known and defined value for our option argument, if the function gets called with out arguments. You can see that very often in plugin code for instance.

Looks more like it's ensuring that something is an object you can hang things on. Setting a default.

Once you call var something or set it as a parameter of the function all instances of something in that scope are the new variable, you can't access the instance in the higher scope.

(function() {
  var something = 'foo';

  (function() {
    var something = something || 'bar';

    console.log(something);
  })();

  console.log(something);
})();

will output

'bar'
'foo'

The OR constructor in javascript is close to this function

function or(a, b)
{
  if(a) return a;
  else return b;
}

When "a" evaluates to true, it doesn't even check for "b" (nor executes it, but it is not the function case). Moreover, it returns pure "a" without changing it into boolean. The construction of non-boolean variables "ORed" evaluates to the first that turns into boolean true. It is widely used in places, when something can be not supported.

var functionDoingSomethingCrossBrowser = functionOnMsie 
                                      || functionEverywhereElse;

This coupled with {} (new object) operator fills the variable with empty object when your "something" is not available in scope (most probably undefined, which evaluates to false).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top