Anjan Dutta

Scope in javascript an introduction for beginners

Scope in javascript an introduction for beginners

A scope in javascript, is the block of code where a variable or function has it’s access or visibility.

In javascript, the scope of variable works in a little different way. A variable or function at first looks for any value in the local scope.

1var a = 10;
2
3function print() {
4 a = 15;
5 console.log(a); //15, local scope gets precedence
6}

If a variable don’t have a value in the local scope, the javascript engine moves to it’s parent scope to look for the value of that variable and so on until it reaches to the global scope.

1var a = 10;
2
3function print() {
4 console.log(a); //15, local outer scope gets precedence
5}

Types of scope in Javascript

There are three types of scope in javascript. Block scope, function scope and lexical scope.

Block scope

Now, what is a block scope? In Javascript, we can separate a block of code using two curly brackets { }.

In general a block doesn’t do much rather than separating the code for a better readability.

But, in ES6, there are 2 keywords, let and const. These are the block scope identifiers.

Using these two keywords, if we declare a variable inside any block, then that block becomes the scope of those variables. See the below example.

1var a = 1;
2var b = 2;
3{
4 let a = 0;
5 var b = 10
6 // write whatever code you want to distinguish from the rest.
7 console.log(a); //0
8}
9console.log(a); //1
10console.log(b); //10

See, the value of ‘b’ gets overwritten, but the value of ‘a’ doesn’t.

Function scope

A function scope is the function definition or the function body itself, where all declared variables or functions has it’s access within the function body itself.

Outside of the function, those variables don’t exist. Remember that, global variables can always be accessible from any function or block.

1var a= 10;
2function add() {
3 var b = 5;
4 return a + b;
5}
6
7console.log(b); //reference error

Lexical scope

In javascript, when we write one function within another function body, this is called nesting of functions.

A nested function has access to it’s local scope as well as it’s parent function’s scope. This means, a nested function can access all sibling functions as well as variables declared within it’s parent function.

In this type of scenarios, the parent function’s scope is the lexical scope of the child function.

1function add(a, b) {
2 var c = a + b;
3
4 function print() {
5 console.log(c); // c is accessible in print
6 }
7}

In above example the print function can access the value of variable ‘c’ from the outer function. This is a basic example of lexical scoping.

Conclusion

Scope in javascript is a very important concept. This post will help beginners and advanced level programmers to easily understand Javascript scope.