Month: May 2013

  • JavaScript Constant

    As a good programmer, you make everything constant. By doing so, you limit the places that you can make mistakes, and thus reduce number of bugs… at least works most of the time.

    I wrote an web page for an assignment. Naturally, I used the const keyword all over the place. I did not even think about the possibility that JavaScript has no constant as VIM highlights the keyword, and the page worked perfectly on Firefox and Opera on my machine.

    Therefore, I was very surprised when I found the page bugged out on the tutor’s computer with Google Chrome.

    The story starts with scoping rule of JavaScript. Variables in JavaScript has either global scope or function scope. Nested functions can access variables of the nesting function. This is called scope chain. Unlike most languages, JavaScript does not have a block scope; the following is valid JavaScript code

    function a() {
    if (true) {
    var b = 2;
    }
    alert(b);
    }

    What about constants? What will happen in this piece of code?

    function c() {
    for (var i = 0; i < 4; i++) {
    const j = i;
    alert(j);
    }
    }

    ECMAScript 5, the base language of the current version of JavaScript, has no constants. Constant is a proposed feature of the next version of ECMAScript, Harmony. There is also block-scoped variable in Harmony, declared using the keyword let.

    Firefox 20 treats constant as a block scope variable; Opera 12 does not distinguish between constants and variables (you can reassign a “constant”). My code works in both cases. In Chrome / Chromium 26, however, constants have function scope. You can declare a constant in a loop, the constant will not update its value at all. The above code will alert 0 four times. What makes this worse is Chrome / Chromium will not complain the failure of assignment.

    ECMAScript 6, can you standardize a bit faster?