Tuesday, 25 January 2011

Javascript: Type and Value Comparison

A common problem when doing value comparison inside of Javascript is the automatic type conversion that happens for you, this means all the following statements resolve to "true".

  • 1 == 1;
  • 1 == '1';
  • 1 == "1";

As a little bonus snippet in a post by Steve Wellens he provides an answer to the problem, the triple equals ("===") and it's corresponding not equal ("!==").  These comparison operators perform a type check as well as a value check.  This means that a string value will nolonger equal it's corresponding numeric value as the type check will return false.  A useful bit of functionality to have.

No comments:

Post a Comment