What do two vertical lines in an object value mean in javascript? [duplicate]

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?

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), then new Date() is evaluated and assigned to time.

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.


Read More:   Detecting class change without setInterval

The way the operator || is evaluated is that if the first part is true-ish, it returned it. If the first part is false-ish, it returns the second.
The above expressions is therefore equivalent to:

if ($(el).data('start')) {
  time = $(el).data('start');
} else {
  time = new Date();

It means logical sum. var time = $(el).data('start') || new Date(); if $(el).data('start') will have undefined or false value then time will have value from new Date function.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts