Things You Should Know About JavaScript

I know some people cringe at the idea of writing JavaScript. They opt to write CoffeeScript instead and make every attempt to avoid looking at those funny looking mustaches.

It is however, advantageous to learn JavaScript and learn the advanced features, even the odd things about the language. Here’s a collection of things you should know:

  1. Short-hand syntax for creating Arrays and Objects

    Prefer to use [] for arrays and {} for objects instead of new Array() and new Object().

    Other than being syntactically shorter, particularly new Array() yields different results depending on the arguments you provide.

    Passing a single Number argument will change the length of the array after instantiation.

    var array = new Array(2);
          array.length;  // 2

    I’m not sure why you would do this because arrays in JavaScript are dynamic. Passing in a single argument that is not a Number or passing more than one argument will instantiate the array with the arguments provided.

    var array1 = new Array(true);
          array1;  // [true]
    
          var array2 = new Array(1, "a", {});
          array2;  // [1, "a", {}]

    Objects are easier to build when using the short-hand syntax.

    var object1 = { key1 : 'value1', key2 : 'value2' };
    
          var object2 = new Object();
          var object.key1 = 'value1';
          var object.key2 = 'value2';

  2. dot notation vs. subscript notation (bracket notation)

    You can call properties/methods using dot notation or subscript notation.

    var object = {
            value : 42,
            fn : function() {
              return "hello world";
            }
          }
    
          object.value;  // 42
          object["value"];  // 42
          object.fn();  // "hello world"
          object["fn"]()  // "hello world"

    You might ask why you'd ever want to use subscript notation. Subscript notation allows for dynamic creation of properties and methods. So if you ever do any sort of metaprogramming, you'll most likely be using the subscript notation.

  3. === and !===

    CoffeeScript has this right. Prefer === and !== over == and !=. The reason for this is due to type coercion when using the equality operator.

    "0" == 0;  // true
          "0" == false;  // true
          undefined == null;  // true
          " \t\r\n" == 0;  // true

    JavaScript considers 0 and "" to be falsy unlike Ruby. If the strict equality operator (===) was used in the above examples, they would all return false.

  4. Function Scope, The Only Scope

    if (true) {
            var SomeObject = {};
          }

    What is the value of SomeObject outside of the if statement? Is it undefined? Or {}?

    Believe it or not, code wrapped in m̶u̶s̶t̶a̶c̶h̶e̶s̶ curly braces does not have scope. Only functions create scope. Therefore, SomeObject is {}.

    function a() {
            var b = 1;
          }
    
          a();
          b;  // ReferenceError

  5. Hoisting

    if (!SomeObject) {
            var SomeObject = {};
          }

    For this example, what is the value of SomeObject? Is it undefined? Or {}? Or some Error? This is probably one of the most interesting parts of JavaScript. Right before the code is executed, all variable declarations are hoisted to the top of the given scope. The example above turns into this before execution:

    var SomeObject;
    
          if (!SomeObject) {
            SomeObject = {};
          }

    So, the value of SomeObject is {}. Similarly, function declarations are hoisted to the top as well. This example:

    abracadabra();
          function abracadabra() {
            var magic = "it works!";
          }

    works because it looks like this before execution:

    function abracadabra() {
            var magic = "it works!";
          }
          abracadabra();

    It's magic!

  6. Casting Values

    There are several ways to cast a primitive value. The simplest way is to use the String, Number, Boolean functions:

    String(42);  // "42"
          Number("42");  // 42
          Boolean("true");  // true

    Cool kids like to use this approach, which works the same way:

    // cast string to number using the plus operator
          +"42";  // 42
    
          // cast number to string using an empty string and coercion
          "" + 42;  // "42"

  7. Using Number methods on Number literals

    Ever wondered why you can call String methods on String literals, but not Numbers?

    "1 2 3".split(" ");  // ["1", "2", "3"]
    
          2.toFixed();  // SyntaxError

    According to the JavaScript Garden documentation, it's because a flaw in JavaScript's parser tries to parse the dot notation on a number as a floating point literal. The best way to handle this issue is to wrap the Number literal in parentheses.

    (2).toFixed();  // "2"

  8. arguments object is not an Array

    The arguments object has a length property, but it is not an Array. Therefore, you cannot directly call Array methods from the arguments object. The best way to do this is to use call or apply.

    Array.prototype.shift.call(arguments);

  9. Privatizing variables

    With closure, you can create privatized variables in JavaScript.

    var fn = (function() {
            var privatizedVariable = "private";
            return function() {
              return privatizedVariable;
            };
          })();
    
          fn();  // "private"
          privatizedVariable;  // ReferenceError

There are a ton more advanced features that everyone should know that are outside the scope of this post (or my lack of explaining it better than the books/articles out there):

  1. Prototypal inheritance
  2. call and apply
  3. function expressions vs. function declarations vs. named function expressions
  4. Name Resolution Order

You can read more about them below.

Master your JavaScript-Fu. Enjoy.

Reference

  1. JavaScript Garden
  2. JavaScript Patterns
  3. JavaScript Scoping and Hoisting
  4. Dmitry's JavaScript Quiz
  5. Kangax's JavaScript Quiz
  6. Named Function Expressions Demystified
  7. Douglas Crockford's JavaScript: The Good Parts
  8. Why of WAT
Steve Kim, Software Craftsman

Steve Kim is fascinated with Smalltalk, Android development, coffee, and the Oxford comma.