Jump to content

JavaScript does not cast strings to boolean consistently?


Mike3456

Recommended Posts

In JavaScript, any non-empty string is supposed to evaluate to true, e.g.

 

Boolean("0"); // true

Boolean("1"); // true

Boolean("2"); // true

Boolean("a"); // true

 

However, in comparisons where casting is required, JavaScript does not evaluate correctly, e.g.

 

(true == "0") // false

(true == "1") // true
(true == "2") // false
(true == "a") // false

 

As you can see, the string "1" with digit 1 seems to be very special and evaluates to true while the others to false

 

Link to comment
Share on other sites

This is because in the first case you're casting strings to boolean. In the second case the interpreter is actually casting from boolean to a number.

When numeric strings are compared using ==, Javascript converts them to numbers, when booleans are cast to number, false is 0 and true is 1. The result is the odd behavior you're seeing

Step 1: What you start with: (true == "1")
Step 2: Cast numeric string to number: (true == 1)
Step 3: Cast true to number: (1 == 1)
Step 4: Compare numbers: (true)
Step 1: What you start with: (true == "2")
Step 2: Cast numeric string to number: (true == 2)
Step 3: Cast true to number: (1 == 2)
Step 4: Compare numbers: (false)

If you want to test the truthiness of a value, just put it straight in the if() statement or while() loop without comparing it to anything:

if("2") {
  alert("true");
} else {
  alert("false");
}
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...