{"id":987,"date":"2009-08-11T20:20:05","date_gmt":"2009-08-12T01:20:05","guid":{"rendered":"http:\/\/unitstep.net\/?p=987"},"modified":"2009-08-11T20:20:05","modified_gmt":"2009-08-12T01:20:05","slug":"evaluation-of-boolean-values-in-javascript","status":"publish","type":"post","link":"https:\/\/unitstep.net\/blog\/2009\/08\/11\/evaluation-of-boolean-values-in-javascript\/","title":{"rendered":"Evaluation of boolean values in JavaScript"},"content":{"rendered":"

If you have a background in a strongly-typed language such as Java, you’ll be used to using logical operators only with boolean values\/expressions. However, in most dynamically-typed languages this doesn’t have to be the case, due to the nature of dynamic typing: The type of the variable is often determined based on the context<\/em> in which it is used.<\/p>\n

With JavaScript<\/strong> there are actually two concepts at play when using logical operators: What is actually returned from the result of a logical operation, and how variables are converted to boolean values when the context requires it.<\/p>\n

<\/p>\n

Undergoing a conversion<\/h2>\n

Firstly, we’ll look at how variables in JavaScript are converted to boolean values. One way to explicitly convert a non-boolean value to a boolean one in JavaScript is to use the global Boolean object as a function<\/a>. By using the following code, you can explicitly get the boolean conversion of a variable or expression:<\/p>\n

var asBoolean = Boolean(someVariable);<\/code><\/pre>\n

The variable asBoolean<\/code> is now guaranteed to have a boolean value. Note that this is not the same as the expression new Boolean(someVariable)<\/code>, as that returns a Boolean (wrapper) object representing the converted value of someVariable<\/code>, not a boolean primitive.<\/strong><\/p>\n

So what values of someVariable<\/code> will result in true<\/code> being returned, and which ones will result in false?<\/code> The following values will evaluate to false<\/code>, while all others will evaluate to true<\/code>:<\/p>\n