Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptJavaScript ES2015: Block Scoping

JavaScript ES2015: Block Scoping

In this article, we will see what is Block scoping in Javascript, access to the block-scoped variables, how it is distinct from other kinds of variable’s scope, through the examples. Prior to ES2015, JavaScript supported only function-level scoping unlike other languages like C++/Java which has block-level scoping. With ES2015, in addition to function-level scoping, JavaScript also supports block-level scoping with the help of the let keyword & const keyword.

But before we get into details of ES2015 stuff, let’s discuss what we exactly mean by phrases “function-level scope” and “block-level scope”.

Block Level Scope: This scope restricts the variable that is declared inside a specific block, from access by the outside of the block. The let & const keyword facilitates the variables to be block scoped. In order to access the variables of that specific block, we need to create an object for it. Variables declared with the var keyword, do not have block scope.

For instance, consider the below example:

{
   let p = 110;
   const q = 111;
}
console.log(p); // Uncaught ReferenceError: p is not defined
console.log(q); // Uncaught ReferenceError: q is not defined

Here, we have used the let & const keyword to illustrate the block-level scope, in order to access the variable from outside of the block.

Function level Scope: The variables in this scope level are restricted to access only the inside the function where it is declared ie., it can be accessed anywhere inside of that function, not accessible outside functions. Every time a new scope will be generated while creating a function & in that scope, any variable can be accessed by any function within that scope. The function or variables defined as global scope will be accessible by all the other variables or functions. Now, let’s look at the function scope in JavaScript.

function printIfGFG( text){
   if(text=="neveropen"|| text=="GFG") {
   var message = "Verified Geek";
   console.log(message); // Output: Verified Geek
}
console.log(message); // Output: Verified Geek
}
printIfGFG("GFG");

In the code snippet above, we have declared and defined a variable message inside the if-condition. Then, displayed the output the value using console.log() function.

The tricky part is the fact that we can also able to print the value of variable ‘message’ outside the if-condition. This is because in JavaScript variables declared using the keyword ‘var’ have to function scope, by default. JavaScript runtime looks for the closest enclosing function relative to the variable declaration and sets it as the scope for that variable.

But, how JavaScript runtime does this? Well, it is worth mentioning here that JavaScript runtime internally changes our code and moves all variable declarations to the starting of the function. This is known as variable hoisting. So, our code in the current example is effectively changed to the below code snippet.

function printIfGFG( text){
   var message;
   if(text=="neveropen"|| text=="GFG") {
   message = "Verified Geek";
   console.log(message); // Output: Verified Geek
}
console.log(message); // Output: Verified Geek
}
printIfGFG("GFG");

To dive deeper into the concept of variable scopes in JavaScript prior to ES2015, refer to the Understanding variable scopes in JavaScript article for further details.

So now when we are clear with what is function scope and block scope, let’s see how ES2015 achieved block scopes in JavaScript. From ES2015, in addition to keyword var, two new keywords are available to declare variables.

Let: Variables declared using the ‘let’ keyword are similar to variables declared using the ‘var’ keyword with just one difference. Variables declared using ‘let’ will have block scope and will not get hoisted to the starting of the function. So, if we try to access those variables outside their block scope, we’ll get a reference error saying the variable is not defined.

function printIfGFG( text){
   if(text=="neveropen"|| text=="GFG") {
   let message = "Verified Geek";
   console.log(message); // Output: Verified Geek
    }
console.log(message); // Output: Uncaught ReferenceError: message is not defined
}
printIfGFG("GFG");

Also, variables declared with the “let” keyword can be redefined but not redeclared.

let msg = "Try again";
msg = "Try again later"; // Output: Try again later
let msg = "Try again";
let msg = "Try again later"; // Output: Uncaught SyntaxError: 
Identifier 'msg' has already been declared

Const: Variables declared using the “Const” keyword are similar to variables declared using the “let” keyword with an additional feature that once declared and defined, their value cannot be changed.

A constant variable in JavaScript is a variable that has a constant or a fixed value which remains the same ie. which does not change throughout the program. Any kind of modification in its value is not possible once it is declared. If the programmer tries to modify its value the compiler shows an error, this is because as soon as we have declared a variable as constant it tells the compiler that this is a fixed value and should be prevented from making any changes to it.

The primary use of Const variables is to make read-only constants like

const PI = 3.14
const MAX_USERS = 1000;

Also, it is compulsory to define const variables at the time of declaration itself.

const pi; // Syntax Error
pi = 3.14

So in this tutorial, we looked upon two new keywords which can be used to declare variables in JavaScript. Once you start using these keywords while declaring variables, there will be rare cases where you will need to use the ‘var’ keyword again.

RELATED ARTICLES

Most Popular

Recent Comments