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

3.6k views Asked by At
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.

7

There are 7 answers

6
Danny Delott On BEST ANSWER

This one-liner is the equivalent of saying:

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

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.

0
Junle Li On

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 : ''.

0
Mic Jaw On

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.

1
amulya349 On

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/

2
TaoPR On

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)

0
Stephen Burke On

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