YDKJS: Scopes & Closures

Chapter 2. Lexical Scope

In the previous chapter the scope was defined.

The engine looks up for the variable in the current scope and if it fails it will continue the search in the upper scopes recursively. Scope look up stops if it finds the first match.

In JS there are two commands that can change that logic.

eval()

The function eval() takes the string as an argument and treats its content as a part of the program. So the JS program can generate it’s content on the run and execute it immediately.

I used the function once when I had algebraic operator as an input string. It was just eval(“x=a”+operator+”b”). Instead I could use four-store switch operator. In my eval() function the IDE issued a warning that its using is dangerous.

The the interesting thing with eval() happens when it declares variables. Consider the next code

function foo(str, a) {
 eval( str ); // cheating!
 console.log( a, b );
}
var b = 2;
foo( “var b = 3;”, 1 ); // 1 3

It declares new variable b and assigns 3 to it. But it is declared in the foo-function scope, so the variable b in the global scope is not changed and is equal 2.

Strict mode

In strict mode any variable declared considered to be in its own scope. So if that variable will be called outside eval(), the ReferenceError will be issued.

with

Let’s start with the example

var obj = {
a: 1,
b: 2,
c: 3
};
// more “tedious” to repeat “obj”
obj.a = 2;
obj.b = 3;
obj.c = 4;
// “easier” short-hand
with (obj) {
a = 3;
b = 4;
c = 5;
}

With operator is working like a multiplier — it applies to every variable. At least tries to apply it. If the object doesn’t have the property x, than the global variable x will be created, and it can create issues.

Strict mode

Well, that’s easy.

In strict mode with is forbidden.

Performance

Usually JS compilators does some optimization while compiling. But if there are eval() or with in the program, the compiler just can’t be sure that it does not spoil the program, so it just doesn’t do it.

Programs with eval() and with works slower.

Review

Do not use eval() or with unless you absolutely have to.

Like what you read? Give Natalia Konovalova a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.