Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Or symbol for JavaScript object declaration

Tags:

javascript

I just started to read some JavaScript project. Most of the .js file to start with have an object declared as the following:

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

What does the || symbol do here?

like image 560
user1240679 Avatar asked Dec 22 '22 00:12

user1240679


2 Answers

Objects in Javascript are truthy, so that expression evaluates to either window.Example or the default object if window.Example is falsy (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 explanation on truthy/falsy and short-circuit evaluation.

like image 155
Paul Avatar answered Jan 08 '23 19:01

Paul


The || operator in JavaScript is like the "or" operator in other C-like languages, but it's distinctly different. It really means:

  1. Evaluate the subexpresson to the left.
  2. If that value, when coerced to boolean, is true, then that subexpression's value (before coercion to boolean) is the value of the || expression
  3. Else evaluate the right-hand subexpression and yield its value as the value of the || expression.

Thus it's used idiomatically to initialize something that might already be initialized:

var something = window.something || defaultValue;

just means, "check to see if "something" is a property of the window object with a truthy value, and if it's not, then set it to defaultValue."

like image 36
Pointy Avatar answered Jan 08 '23 20:01

Pointy