Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "variable = variable || {}" mean in JavaScript [duplicate]

Tags:

javascript

What does this initialization of a variable stand for:

var variable = variable  ||  {} ;

How and when should it be used?

like image 719
iuzzef Avatar asked Apr 05 '13 21:04

iuzzef


People also ask

What are JavaScript variables?

JavaScript variables are containers for storing data values. In this example, x, y, and z, are variables, declared with the var keyword: Before 2015, using the var keyword was the only way to declare a JavaScript variable.

What is the difference between Var and = in JavaScript?

And here’s what’s happening in the example above: 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 are the rules for variable names in JavaScript?

Variable names are pretty flexible as long as you follow a few rules: Start them with a letter, underscore _, or dollar sign $. After the first letter, you can use numbers, as well as letters, underscores, or dollar signs. Don’t use any of JavaScript’s reserved keywords.

How to create a variable in JavaScript with no value?

var answer = 'Yes I am!'; Creating a variable in JavaScript is called "declaring" a variable. You declare a JavaScript variable with the var keyword: After the declaration, the variable has no value (technically it has the value of undefined ). To assign a value to the variable, use the equal sign:


3 Answers

That line of code does the following:

IF variable is not defined (or has a falsey value) THEN set it to an empty object.

ELSE do nothing (technically speaking, variable gets assigned to itself)

In other words variable will be converted to an empty object if it is any of the following:

  • false
  • undefined
  • null
  • zero
  • NaN
  • an empty string

See toBoolean for the spec's definition of falsey values.

like image 78
jahroy Avatar answered Oct 06 '22 20:10

jahroy


If variable is undefined or false, it initializes it to an empty object.

like image 27
Schleis Avatar answered Oct 06 '22 19:10

Schleis


It is to test if variable is initialized. If not, it initializes variable as an empty object. If it does exist, it does nothing, (technically assigns variable to itself).

like image 29
RestingRobot Avatar answered Oct 06 '22 20:10

RestingRobot