1.

Scope and Scope Chain in JavaScript

Answer»

1. Scope: The accessibility or visibility of variables in JavaScript is referred to as scope. That is, which sections of the program can access a given variable and where the variable can be seen. There are usually three types of scopes:


  • Global Scope: The global scope includes any variable that is not contained within a function or block (a pair of curly braces). Global scope variables can be accessed from anywhere in the program. An example showing the global scope of a variable is given below:
var hello = 'Hello!';
function sayHello() {
console.log(hello);
}
// 'Hello!' gets logged
sayHello();

  • Local or Function Scope: Variables declared inside a function are local variables. They can only be accessed from within that function; they are not accessible from outside code. An example showing local scope of a variable is given below:
function sayHello() {
var hello = 'Hello!';
console.log(hello);
}
// 'Hello!' gets logged
sayHello();

console.log(hello); // Uncaught ReferenceError: hello is not defined


  • Block Scope: Unlike var variables, let and const variables can be scoped to the nearest pair of curly brackets in ES6. They can't be reached from outside that pair of curly braces, which means they can't be accessed from the outside. An example showing the block scope of a variable is given below:
{
let hello = 'Hello!';
var language = 'Hindi';
console.log(hello); // 'Hello!' gets logged
}
console.log(language); // 'Hindi!' gets logged
console.log(hello); // Uncaught ReferenceError: hello is not defined

2. Scope Chain: When a variable is used in JavaScript, the JavaScript engine searches the current scope for the variable's value. If it can't find the variable in the inner scope, it will look into the outer scope until it finds it or reaches the global scope.

If it still can't identify the variable, it will either return an error or implicitly declare the variable in the global scope (if not in strict mode). Let us take into consideration the following example:

let a = 'a';
function foo() {
let b = 'b';
console.log(b); // 'b' gets logged
console.log(a); // 'a' gets logged
randomNumber = 33;
console.log(randomNumber); // 33 gets logged
}
foo();

When the function foo() is called, the JavaScript engine searches for the 'b' variable in the current scope and finds it. Then it looks for the 'a' variable in the current scope, which it can't find, so it moves on to the outer scope, where it finds it (i.e global scope).

After that, we assign 33 to the 'randomNumber' variable, causing the JavaScript engine to search for it first in the current scope, then in the outer scope.

If the script isn't in strict mode, the engine will either create a new variable called randomNumber and assign 33 to it, or it will return an error (if not in strict mode).

As a result, the engine will traverse the scope chain till the time when a variable is found.




Discussion

No Comment Found