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?
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.
The ||
operator in JavaScript is like the "or" operator in other C-like languages, but it's distinctly different. It really means:
true
, then that subexpression's value (before coercion to boolean) is the value of the ||
expression||
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With