Search code examples
javascriptconditional-operatorshort-circuiting

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.


Solution

  • This one-liner is the equivalent of saying:

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