Pouya Sanooei
Pouya Sanooei

Reputation: 1022

One-line short-circuit evaluation with && || in JavaScript

var prefix = options && options.prefix || '';

In JavaScipt in my case. Can someone explain what kind of statement or condition is this? Or at the end what's the value of prefix variable?

I know about (ternary operator):

condition ? expr1 : expr2

but this was different.

Upvotes: 1

Views: 3665

Answers (7)

Stephen Burke
Stephen Burke

Reputation: 459

If prefix is available on options, set it to var prefix. Otherwise, set it to an empty string.

Upvotes: 0

TaoPR
TaoPR

Reputation: 6052

Translated into human language

If variable optionsis defined with some non-falsey value

and it also has a property options.prefix whose value is also non-falsey

then set the variable prefix with this options.prefix value.

Otherwise, our prefix is set to empty string by default.


PS. Quickly check the complete list of falsey values in JavaScript by google "javascript falsy values"


Quicker explanation

This is a quick value check (and get) of options.prefix which is empty string by default.

(without throwing an exception when options is undefined)

Upvotes: 1

amulya349
amulya349

Reputation: 1238

Its similar to following:

var prefix;
if(options){     // or for better understanding, its if(options != undefined)
    prefix = options.prefix;
}
else
    prefix = '';

Try the following fiddle for better understanding: http://jsfiddle.net/n41tfnh4/1/

Upvotes: 1

Mic Jaw
Mic Jaw

Reputation: 366

The reason this works is in Javascript logical operators evaluate to the value of the last operand.

So is options object exist, the && part of the expression will be evaulated to options.prefix.

If that is not set, the left part of the || expression will be false and the right part = the '' string - will be returned.

Upvotes: 1

Junle Li
Junle Li

Reputation: 1035

It means, it options is an object, use options.prefix. If options.prefix is undefined or null or other falsy value, return empty string.

Nearly same meaning of options ? options.prefix : ''.

Upvotes: 0

wicker95
wicker95

Reputation: 131

The statement is setting the variable "prefix" to either the value of "options.prefix", or an empty string, in such a way that if "options" does not exist, it does not throw an error.

Upvotes: 3

Danny Delott
Danny Delott

Reputation: 6998

This one-liner is the equivalent of saying:

var prefix;
if(options && options.prefix){
  prefix = options.prefix;
} else{
  prefix = '';
}

Upvotes: 6

Related Questions