简体   繁体   中英

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.

This one-liner is the equivalent of saying:

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

该语句将变量“ prefix”设置为“ options.prefix”的值或空字符串,这样的方式是,如果“ options”不存在,则不会引发错误。

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.

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/

Translated into human language

If variable options is 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)

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 : '' options ? options.prefix : '' .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM