Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Syntax empty {}

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
}
like image 449
Leoa Avatar asked Dec 03 '25 11:12

Leoa


2 Answers

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();
}
like image 95
antyrat Avatar answered Dec 06 '25 02:12

antyrat


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.

like image 21
Andries Avatar answered Dec 06 '25 04:12

Andries



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!