Possible Duplicate:
What does the || operator do?
Maybe somebody can provide a better code snippet, but what does ||
mean in the following?:
var time = $(el).data('start') || new Date();
Is it an or
operator and if so, how does it make sense that a variable can have two different values?
The vertical bar character (|), located over the backslash (\) key, is used as an OR operator. In the C/C++ language, two vertical bars are used; for example, if (x == 'a' || x == 'b') means "if X is equal to A or B." It is also used as a pipe symbol, which directs the output of one process to another.
The double pipe operator (||) is the logical OR operator . In most languages it works the following way: If the first value is false, it checks the second value. If it's true, it returns true and if it's false, it returns false.
This is an OR
operator. What you need to understand is:
Non-boolean values are converted to a boolean when used in a logic operator. Values that convert to false
are called "falsy" and values that convert to true
are called "truthy". Falsy values include things like 0
, undefined
, null
, and so on. See more at Truthy and Falsy: When All is Not Equal in JavaScript.
The OR
operator short-circuits: it keeps evaluating expressions until it finds on that is true
, and then stops.
So, var time = $(el).data('start') || new Date();
means "set time
to the start
data of the el
element, OR, if that's falsy, use the current time".
exp1 || exp2
evaluates exp1. If exp1 is true then exp2 is not evaluated (known as short circuit evaluation). If exp1 returns false then exp 2 is evaluated. If exp1 OR exp2 is true then (exp1||exp2) evaluates as true.
But in Javascript, you can set values using the operator.
a = something
if (prop)
a = prop
can be rewritten as
a = prop || something
It means 'or'. In this instance it assigns the value of $(el).data('start')
to the variable time
or, if that doesn't exist or instead returns false
, it assigns instead the value returned from new Date()
. Or, as more clearly noted by Malovolio, in comments:
...if
$(el).data('start')
is "falsy" (that is, undefined, null, 0, false, an empty string, or NaN), thennew Date()
is evaluated and assigned totime
.
The important aspect of a logical operator:
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.
References:
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