Or a JavaScript object declaration symbol

I just started reading some kind of JavaScript project. Most .js files have, for starters, an object declared as the following:

window.Example || { bleh: "123"; blah: "ref" } 

What does the symbol || ?

+4
source share
3 answers

Objects in Javascript are true, so the expression evaluates to either window.Example or the default object if window.Example is false (or undefined). Example:

 var x = window.Example || {foo: 'bar'}; // x = {foo: 'bar'}, since window.Example is undefined window.Example = {test: 1}; var y = window.Example || {foo: 'bar'}; // y = {test: 1}, since window.Example is truthy (all objects are truthy) 

Read this article for a good truth / falsification and short circuit assessment.

+6
source

Operator || JavaScript is similar to the "or" operator in other languages ​​like C, but it is distinctly different. It really means:

  • Rate the subexpression on the left.
  • If this value when enforced to a boolean value is true , then this value of the subexpression (before coercion to a boolean) is the value of the expression ||
  • Else evaluates the right subexpression and displays its value as the value of the expression || .

Thus, he idiomatically used for initialization what can already be initialized:

 var something = window.something || defaultValue; 

just means: "check to see if" something "is a property of a window object with a true value, and if not, set its default value."

+3
source

There is no important bit in this code - a variable declaration:

 var something = window.Example || { bleh: "123", blah: "ref" } 

This roughly translates to "set something in window.Example if it does not exist, then set it for this new object."

+2
source

Source: https://habr.com/ru/post/1403722/


All Articles