Search code examples
javascriptobjectstatements

Difference between two statements that declare an object


What is the difference between this statement

var X = X || {};

And this. They do the same thing? There is a performance difference?

var X = typeof X === "undefined" ? {} : X;

Solution

  • They're not the same.

    The || will return the object when X is any possible falsy value.
    The typeof check will only return {} if is X is undefined.

    According to this test, the undefined check is nearly twice as fast. That's probably because no type casting is required.