3

I'm trying to figure out what does the empty {} mean.

var $sb = $sb || {};

Does this mean that varaible $sb's value is either copied to itself or it is a function literal?

full context:

var $sb = $sb || {};
$sb.xxx = function() {
    // code
}

5 Answers 5

5

It's shortcut for

new Object()

So this line

var $sb = $sb || {};

Will check if variable $sb exists and if not create new object and assign it to $sb variable.

So in other way you can write this like:

if( !$sb ) {
    var $sb = new Object();
}
Sign up to request clarification or add additional context in comments.

Comments

4

var a = {} is called the object literal notation. It's a faster than var a = new Object() because it needs no scope resolution (ie you could have defined a constructor with the same name and therefor the JavaScript engine must do such a lookup).

The pattern var a = a || {}; is used to avoid replacing a in case you have already defined a. In this pattern, the or-operator: || functions as a coalescing operator. If a is null or undefined it will execute the expression at the right-hand of the statement: {}

Using this pattern ensures you that a will always be defined as an object and, in case it already exist, will not be overwritten.

Comments

2

It's an object literal. Like:

var obj = { x: 4, y: 2 };

only there are no properties:

var obj = {};

The || operator returns the first operand if it evaluates to a non-falsy value, otherwise it returns the second operand. So the expression $sb || {}; returns the value of $sb if it exists, otherwise it creates a new empty object.

Comments

1

It is the abbreviation for new Object()

Comments

1

It's short for:

new Object()

In this case, this means $sb will be set to it's own value, or to a new, empy object in case $sb is undefined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.