JavaScript tip – Implicit conversion

  1. isSomething = function(val) {
  2. if (val == undefined || val == null || val == "") return false;
  3. return true;
  4. };

Spot the problem? Give up? This JavaScript function is being used to test if passed objects contain (useful) data. But what about zero? is that useful? This function says not – passing a zero will result in a return value of false. Why? Because when comparing two objects using the == comparator, JavaScript uses implicit conversion. So a 0 == false comparison results in true. Now, you may want that implicit conversion, but most probably what you want it to not implicitly convert the compared values to comparable types. In that case what you need is the “===” operator (extra “=”) . Try it in your JavaScript console: 0 === false evaluates to false while 0 == false evaluates to true. The corrected function should thus read:
  1. isSomething = function(val) {
  2. if (val === undefined || val === null || val === "") return false;
  3. return true;
  4. };