javascriptvariable-assignmentlogical-operatorscontrol-structure

Testing for null object using short-circuit logical operator


I'm reading through the Mozilla Developer Network's page on Javascript, and am confused by a line I see. Here's the description and line in question:

The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:

var name = o && o.getName();

My confusion here is that, presumably the purpose of the snippet is to perform:

var name;
if (o){
     name = o.getname();
}  

However, it looks like what happens here is that name is being assigned a boolean, and that boolean is "o exists and its name is not empty". In other words, to me it looks like:

var name = false;
if (o && o.getname()){
    name = true;
}

Thanks!


Solution

  • This answer is the comment of Felix Kling and I hope that he will post it as his own answer to get the rewarded reputation


    Have a look at Logical Operators, at the very top:

    "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."