javascript

Scope in Javascript an Introduction for Beginners

Intro

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.

var a = 10;

function print() {
a = 15;
console.log(a); //15, local scope gets precedence
}

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.

var a = 10;

function print() {
console.log(a); //15, local outer scope gets precedence
}

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.

var a = 1;
var b = 2;
{
let a = 0;
var b = 10
// write whatever code you want to distinguish from the rest.
console.log(a); //0
}
console.log(a); //1
console.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.

var a= 10;
function add() {
var b = 5;
return a + b;
}

console.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.

function add(a, b) {
var c = a + b;

function print() {
console.log(c); // c is accessible in print
}
}

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.

Leave a Comment

eighty four − = seventy six