JavaScript catch clause scope

If I understand it right, then what it probably means is that, in your code,

try {
    console.log(y); //ReferenceError so we enter catch
} 
catch(e) {
    var x = 10;
    console.log(x); //10
}

e will only exist in the catch block. Try console.log(e); outside the catch block and it will throw ReferenceError.

As with WithStatement, with ({x: 1, y: 2}) { }, x and y will only exist inside the with block.

But it doesn’t mean that var declarations will be bound to the closest lexical environment. Actually, var declarations will be bound to the environment when entering an execution context.

10.5 Declaration Binding Instantiation: when the execution context in being entered, it will look for function declarations, arguments, and variable declarations and then create bindings in the execution context’s VariableEnvironment.

So any variables that are declared using var will be accessible anywhere in the function regardless of the control structures or where it is defined inside the function. Note that this does not include nested functions as they’re a separate execution context.

That means the var declarations will be bound to the closest execution context.

var x = 1;
(function() {
    x = 5; console.log(x); // 5
    if (false) { var x; }
    x = 9; console.log(x); // 9
})();
console.log(x); // 1

So in above code, x = 5; will set the x variable inside the inner function, because var x; inside if (false) { var x; } is bound to that function already before the function code is executed.

Leave a Comment