Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code produce 3 in JavaScript?

Why does the following code produce a == 3?

var x = "abc";
var y = 3;
var z = "xyz";
var a = x && y || z;

http://jsfiddle.net/thinkingmedia/qBZAL/

I would have expected this to result in a == true.

Why is the logical operator evaluating "abc" as true but doesn't evaluate 3 as true. Instead it produces 3 as the result.

Furthermore, if you change y = 0 then a == "xyz" which means that && treated 0 as false. What happen to treating a number as a number?

What's going on here with the logical operators?

like image 891
Reactgular Avatar asked Nov 27 '22 20:11

Reactgular


2 Answers

This is to be expected.

In JavaScript (and many other languages), not only Booleans themselves are true or false, but other objects can be truthy or falsey as well (See the docs on mdn):

The value […] is converted to a boolean value, if necessary. If value is […] is 0, -0, null, false, NaN, undefined, or the empty string (""), [it is] false. All other values, including any object or the string "false", create […] true.

The logical operators || and && don't return true or false, rather they return the last argument to influence whether they are truthy or falsey (reference):

  • expr1 && expr2 – Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
  • expr1 || expr2 – Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
like image 61
amon Avatar answered Dec 05 '22 06:12

amon


  1. The first step is to evaluate "abc" && 3.

    • false && 3 would return false,
    • true && 3 would return 3.

    "abc" is not false, so JavaScript takes the second part, i.e. 3.

The second step is to evaluate 3 || "xyz". Here, JavaScript takes the first value which is not null, i.e. 3. This is similar to this.firstObject ?? this.defaultValue in C#: the second part is taken only when the first part is null.

like image 45
Arseni Mourzenko Avatar answered Dec 05 '22 05:12

Arseni Mourzenko