Posts

Showing posts from 2011

Comparison operators in JavaScript

Another pretty weird but some may argue powerful feature of JavaScript is the way it handles comparisons. In JavaScript, (false==0) , (null==undefined), (""==0) all result in TRUE! Weird? You bet it is! What JavaScript does behind the scene? It uses pretty confusing and complicated set of rules while comparing values. In most cases it just tries to convert one of the values to the type of the other value. However, when null or undefined occur, it only produces true if both sides are null or undefined. For cases where you do not want any automatic type conversions to happen, there are two extra operators: === and !==. The first tests whether a value is precisely equal to the other, and the second tests whether it is not precisely equal. So now, (false===0) , (null===undefined), (""===0) will all return false as expected! Amusing, isn't it? Reference: http://eloquentjavascript.net

Logical operators in JavaScript

Most of us who are more familiar with static typed languages like java, c#, c++, c etc, know that logical "and" and "or" can be applied on boolean values. Well Javascript (or may be even other dynamic languages) let you apply these operators on any type. The way it works : 1. The || ("OR") operator - The expression on the left hand side of the operator is evaluated. If that expression is true, the value on the right is returned as it is which in turn is converted to boolean. So basically something like ("" || "hello") would return "hello" which when converted to boolean returns true. 2. The && operator works similarly, but the other way around. When the value to its left is something that would give false when converted to a boolean, it returns that value, and otherwise it returns the value on its right. (picked straight from this book) The way javascript handles boolean is also pretty odd. Only 0, "", null ...