Javascript logical operators and assignment?

veta
x = 1 || 2;
alert(x);
x = undefined || 2;
alert(x);

Apparently x in the above code doesn't return a boolean value. It returns the first valid value, which is 1 in the first case and 2 in the second case.

Is there any other strangeness like this I should watch out for?

jfriend00

The || operator in Javascript as in x || y will evaluate to the first operands if it is truthy or the second operand if the first one is not truthy. It is documented on MDN here.

truthy in Javascript is described here on MDN. It's basically, anything except one of the falsey values which are:

false
null
undefined
0
NaN
""

So, you have to think of the || operator as something that deals in truthy/falsey, not in pure Booleans.

The operator works as it has been specified and hundreds of thousands of developers have learned it that way and successfully use it. It is not a pure Boolean operator. It does not necessarily return a Boolean value. That is different than some other languages. If you want to call different "strange", you're welcome to your opinion. But, it is what it is and it has always been this way in Javascript.

It's easy to learn what it does and use it for that. There is no real strangeness or unpredictability to its specification or implementation once you understand the design intent.

It is different than some people coming from other languages might expect, but that is not the goal of really any language. Each language has it's own design that must be learned to use it appropriately.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related