JavaScript ES2015: Block Scoping
Last Updated :
18 Nov, 2022
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=="GeeksforGeeks"|| 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=="GeeksforGeeks"|| 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=="GeeksforGeeks"|| 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.
Similar Reads
ES2015: Latest Version of JavaScript
ES2015 is the latest version of JavaScript programming language. It is the first major upgrade to JavaScript since 1997. It was approved in June 2015 by ECMA international, an association responsible for approving ECMA standards which programming languages like JavaScript, CoffeeScript and TypeScrip
4 min read
Scoping & Hoisting in JavaScript
Prerequisite: Understanding Javascript Scoping, Javascript Hoisting In JavaScript, there are two types of scopes Global Scope: Scope outside the outermost function attached to the window.Local Scope: Inside the function being executed. Hoisting: It is a concept that enables us to extract values of v
11 min read
Javascript Scope
JavaScript Scope is the area where a variable (or function) exists and is accessible. We can layer the scope in a system which means the child scope can access the parent scope but not vice-versa. Javascript has different scopesTable of Content Global ScopeFunction ScopeBlock ScopeLexical ScopeGloba
3 min read
JavaScript For Loop
JavaScript for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and increment/decrement. [GFGTABS] javascript // for loop begins when x=2 // and runs till x <= 4 for (let x = 2; x <= 4; x++)
5 min read
What is Variable Scope in JavaScript ?
Variable scope is the context of the program in which it can be accessed. In programming, a variable is a named storage location that holds data or a value. Think of it as a container that you can use to store and manipulate information in your code. Variables allow you to work with data in a flexib
4 min read
JavaScript Nested Classes
Let us try to understand, what is class. A class in JavaScript is a type of function, which can be initialized through both function keywords as well as through class keywords. In this article, we will cover the inner class in javascript through the use of a function keyword. Here's an example of th
3 min read
JavaScript ES5 Object Methods
The ES5 Object method in javascript is used to find more methods to interact with the objects. The ES5 Object method can do: prevents enumeration manipulation deletion prevent addition of new features getters and setters Syntax: Object.defineProperty(object, property, {value : value}) The following
2 min read
Data Privacy Using Closures in JavaScript
Let's first understand what closures are in Javascript. Closures: A function along with a reference to the outer environment together forms a closure. In other words, we can say that it's a combination of a function and its lexical scope bundled together which means the inner function has access to
2 min read
Lexical Scope in JavaScript
Lexical scope is a fundamental concept in programming that determines the accessibility of variables and functions based on where they are defined in the source code. In simple terms, lexical scope is the scope of a variable or function determined at compile time by its physical location in the code
4 min read
New features of JavaScript Arrays with ES2015
In this article, we will be discussing the new additions in ES2015 which substantially improves the way we work with Arrays in JavaScript. Array DestructuringArray destructuring allows us to assign values to variables from an array using syntax similar to the array itself. Letâs look at the code bel
4 min read