Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does var x = x || {} ; [duplicate]

Tags:

javascript

what does the following code do in java script:

var x = x || {}; 
like image 628
jakoh Avatar asked Aug 25 '10 05:08

jakoh


People also ask

What is var x {} in JavaScript?

var is the keyword that tells JavaScript you're declaring a variable. x is the name of that variable. = is the operator that tells JavaScript a value is coming up next. 100 is the value for the variable to store.

What is the meaning of {} in JavaScript?

This means that if window. google doesn't have value (undefined, null) then use {} . It is a way of assigning a default value to a variable in JavaScript. Follow this answer to receive notifications.

What does || mean in typescript?

The double pipe operator ( || ) is the logical OR operator . In most languages it works the following way: If the first value is false , it checks the second value. If that's true , it returns true and if the second value is false , it returns false .

When should I use VAR in JavaScript?

Always declare JavaScript variables with var , let , or const . The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code to run in older browser, you must use var .


2 Answers

|| is the logical OR.

The expression

var x = x OR {}; 

should become more obvious then.

If x has a falsy value (like null, undefined, 0, ""), we assign x an empty object {}, otherwise just keep the current value. The long version of this would look like

var x = x ? x : {}; 
like image 112
jAndy Avatar answered Oct 04 '22 00:10

jAndy


If x is undefined (or null, or any other false value), it becomes an empty object.

like image 30
Gabe Avatar answered Oct 03 '22 22:10

Gabe