Monday, 3 November 2008

Equals, Equals Equals or Equals Equals Equals?

In JavaScript, you often see conditional statements with 3 equals signs (===). I always thought it was a typo but it turns out to have a significant advantage over the traditional 2 equals signs (==). This post shows how to use 1, 2 or 3 equals signs effectively.


Assign and evaluate
 if ( x = y + z ) { alert( "true" ); }

Assigns x to the sum of y and z and evaluates the result.


Compare (irrespective of data type)
 if ( x == y + z ) { alert( "true" ); }

The result of the sum of y and z is compared to x where both sides must have the same value.

Example:
x = "5"
y = 10
z = -5

y + z = 5

Using the above values, the condition will be considered to be true because the sum of y and z is converted to a string prior to the comparison.


Compare and match data types
 if ( x === y + z ) { alert( "true" ); }

The result of the sum of y and z is compared to x where both sides must have the same value and be of the same data type.


To summarise, always use === when doing conditional statements unless you want to compare values of different data types.


* zero and an empty string are considered to be false and all other numbers and strings are considered to be true.

No comments: