What does it mean when you use the || operator to define a variable like
mouse.x = e.clientX || e.pageX;
What is the operator used for?
What does it mean when you use the || operator to define a variable like
mouse.x = e.clientX || e.pageX;
What is the operator used for?
Using this operator in the way you show sets the var to the second value if the first one is falsy.
In your specific example it is a shortcut for
if (e.clientX) mouse.x = e.clientX;
else mouse.x = e.pageX
to avoid accessing e.clientX twice: If clientX is not set, take pageX.
More information about this Logical Operator from MDN:
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.
var e = { "clientX":25,"pageX":35 }
var res = e.clientX || e.pageX; // 25
console.log(res);
e = { "clientX":0,"pageX":35 }
res = e.clientX || e.pageX; // 35, clientX is falsy
console.log(res)
e = { "clientX":0,"pageX":0 }
res = e.clientX || e.pageX; // 0 from pageX, clientX is falsy
console.log(res)
e = { "clientX":0,"pageX":null }
res = e.clientX || e.pageX; // null from pageX, clientX is falsy
console.log(res)
||
is the logical OR operator. It is used when more than one statement may be considered.
if (age > 18 || hasParentalSignature == true) {
// Allowed to attend
}
In Javascript the operator also serves as a Null Coalescing Operator. It is not strictly null coalescing, because it recognizes "falsy" values other than null
, but it is very similar.
Null coalescing is a "if value A is falsy then use B instead" operator. For example:
var x = "Hello!";
var z = y || x;
In this example the y
variable was never defined, which means that it is "falsy", so instead the x
variable will be used.
Using if statements it would be the same as:
var x = "Hello!";
if (y) {
var z = y;
} else {
var z = x;
}
Or using the ternary operator:
var x = "Hello!";
var z = (y ? y : x);
Most other languages, that have a null coalescing operator, use a dedicated operator to do this. In Javascript, for whatever reason, it is part of the OR operator.
This question deals with the OR's null coalescing properties.