endJS

Bugs From Automatic Semicolon Insertion

Some programming languages require semicolons to terminate each line, and some languages don't, those that don't, often just use the new line to know that the statement has terminated. JavaScript however requires semicolons in theory, but will automatically add them in when you forget them. The problem is though, there are many cases where JavaScript will automatically add in semicolons in undesirable places, even if you are trying to be a diligent programmer who puts semicolons in the right places, sometimes JavaScript will sneak them into places which break your code. For example, consider the following function:

let enclose = function(x, y) {
    return
    {
        x: x
    };
};

console.log(enclose(5));

One might expect this to return the object { x: 5 }, but instead it returns undefined. This is because JavaScript automatically inserts a semicolon after the return statement as follows:

let enclose = function(x, y) {
    return;
    {
        x: x
    };
};

console.log(enclose(5));

So the object declaration is actually unreachable code. Not only is unreachable code something checked in many compiled languages, but even if automatic semicolon insertion is permitted, a statically typed language would know there is an error from the type mismatch.

The corrected code requires the first brace to be put on the earlier line so that the semicolon isn't put in:

let enclose = function(x, y) {
    return {
        x: x
    };
};

console.log(enclose(5));