Why does this code generate 3 in JavaScript?

Why is the following code created a == 3?

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

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

I expected this to result in a == true.

Why does a logical operator evaluate "abc"how true, but not evaluate 3how true. Instead, the result is 3.

Also, if you change y = 0, then a == "xyz"that means it is &&treated 0like false. What happens to treating a number as a number?

What happens here with logical operators?

+4
source share
3 answers

This can be expected.

JavaScript ( ) , (. mdn):

[...] boolean, . [...], 0, -0, null, false, NaN, undefined (""), [] false. , "false", [...] true.

|| && true false, , , (reference):

  • expr1 && expr2 - expr1, false; expr2. , && true, ; false.
  • expr1 || expr2 - expr1, true; expr2. , || true, ; false, false.
+15
  • - "abc" && 3.

    • false && 3 false,
    • true && 3 3.

    "abc" , JavaScript , .. 3.

- 3 || "xyz". JavaScript , , .. 3. this.firstObject ?? this.defaultValue #: , null.

+10

a side effect is that you can do things like this:

x = x || {};

to set the default variable if it is not set.

or

TrackingManager && TrackingManager.track("user was here")

to avoid more voluminous if statements.

+1
source

Source: https://habr.com/ru/post/1537884/


All Articles