Richard Hamilton
Richard Hamilton

Reputation: 26444

Why does using "0" with the ternary operator return the first value?

I was playing around with JSconsole and found something strange. The value of "0" is false

"0" == false
=> true

The value of false when used in ternary returns the second value

false ? 71 : 16
=> 16

However the value "0" which equals false when used in ternary returns the first value.

"0" ? 8 : 10
=> 8

However, if you use 0 as the value, it returns the second value

0 ? 4 : 5
=> 5

0 == "0"
=> true

I'm afraid this doesn't make sense to me.

Upvotes: 20

Views: 11974

Answers (4)

Zee
Zee

Reputation: 8488

"0" is a string of length>0 which is true. Try

0 ? 8 : 10

and see. It will return 10.

== does type conversion and hence when you do

"0" == false

it returns true. When you do

0 == "0" //true

It also returns true as again type conversion is taking place. Even though one is a number and the other one is a string it returns true. But if you use ===, no type conversion is done and 0 === "0" will return false.

A nice explanation of == & === is given here.

From the docs:

The equality operator(==) converts the operands if they are not of the same type, then applies strict comparison.

The identity operator(===) returns true if the operands are strictly equal with no type conversion.

Upvotes: 17

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77485

JavaScript leads to tons of WTFs.

Check out "Javascript WTF" on YouTube...

Essentially, you are requesting a conversion from string to boolean.

This is defined as "string is not empty".

Whereas you assumed that javascript does string -> int -> boolean if the string happens to contain a number.

It's sensible. But these automatic conversions lead to programming errors, which is why I prefer typesafe languages (with compile time type checking) for larger projects.

For fun, try these:

("0" * 1) ? 71 : 16
("0" + false) ? 71 : 16

Upvotes: 1

xdazz
xdazz

Reputation: 160953

Non-empty string is considered as truth value in conditional statements, conditional expressions and conditional constructs.

But when you compare a string with a number with ==, some conversion will take place.

When comparing a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.

And == don't have the Transitive Property of Equality:

you can't say if a == b, b == c, then a == c.

An example will be:

"0" == false // true
false == "\n" //true

and guess the result of "0" == "\n"? Yes, the result is false.

Upvotes: 20

Evan Knowles
Evan Knowles

Reputation: 7511

I'm afraid this is an example of why you should use === - plain old == performs type conversion. Try

"0"===false

Upvotes: 6

Related Questions