One of the difficulties in learning JavaScript are all the tricky quirks. With learning any new language, there are always quirks like this but with JavaScript they can especially drive you crazy. Here are the top two issues:

Double Equals is not what you think it is

There are two types of equality tests people can do in JavaScript: double-equals "==" uses type-coercion which attempts to convert the values into similar types; triple-equals "===" does a type-sensitive comparison.

Solution


If you want the same equals you'd find in other languages, you are going to want to use '==='. The consensus on '==' quite frankly is that it should never be used. However for conditionals (if, while, for, etc...) a similar type conversion to boolean is done. This is where type conversions can actually be really convenient, if you do not care about the value being strictly a boolean false and only care if it is not undefined or null or 0 or etc...
// more code
if (a !== undefined || a !== null) {
}
// simpler
if (!a) {
}

The 'falsy' values in javascript are:

  • false
  • 0 (zero)
  • "" (empty string)
  • null
  • undefined
  • NaN (i.e. not a number such as dividing by zero)

Variable Scopes


How variables are scoped can be a bit confusing. Four things to note:
  1. If you do not use the "var" keyword, the value will be set as a property of "window", the browser's global variable.
    value = "test";
    console.log(window.value); //"test"
    

  2. Scope is by function and will be carried into each function unless a new variable is declared with the same name.
    function example () {
      var value = "something";
      function inside () {
        var value = "something else";
        return value;
    } return inside(); } // "something else"

  3. Inside any function, "this" is assumed to be window unless it is declared a property of this. That could be set as a property of the object or as a property of the prototype.
    _value = "Joe";
    function example () {
      this._value = "Fred";
    }
    example.prototype.value = function () {
      return function () {
        return this._value;
      }
    };
    var item = new example();
    item.value() // "Joe"

  4. There is no block scope. A declaration in a for-loop will not create a new variable. It will just change the current variable inside the scope.


Solution

  • always make sure to use different variable names or check for an existing value

    var value = value ? value : newValue;

  • for 'this' issues, take advantage of meta-functions: call, apply, and bind.

It's not all bad


These quirks can be really annoying at first but once you get use to it. When you do hit bugs make sure to:
  • that you are using '==='
  • what is the current 'this', you are accessing
  • do not reuse variable names


Next time I will show one of the real powerful advantages of javascript: manipulating functions. I will talk about callapply, and bind as well as the array iterator methods.

References