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
GeeksforGeeks Practice - Leading Online Coding Platform GeeksforGeeks Practice is an online coding platform designed to help developers and students practice coding online and sharpen their programming skills with the following features. GfG 160: This consists of 160 most popular interview problems organized topic wise and difficulty with with well writt
6 min read
7 Different Ways to Take a Screenshot in Windows 10 Quick Preview to Take Screenshot on Windows 10:-Use the CTRL + PRT SC Keys to take a quick screenshot.Use ALT + PRT SC Keys to take a Screenshot of any application window.Use Windows + Shift + S Keys to access the Xbox Game Bar.Use Snip & Sketch Application as well to take screenshotTaking Scree
7 min read
Artificial Neural Networks and its Applications Artificial Neural Networks (ANNs) are computer systems designed to mimic how the human brain processes information. Just like the brain uses neurons to process data and make decisions, ANNs use artificial neurons to analyze data, identify patterns and make predictions. These networks consist of laye
8 min read
Top 50 Java Project Ideas For Beginners and Advanced [Update 2025] Java is one of the most popular and versatile programming languages, known for its reliability, security, and platform independence. Developed by James Gosling in 1982, Java is widely used across industries like big data, mobile development, finance, and e-commerce.Building Java projects is an excel
15+ min read
Understanding the Confusion Matrix in Machine Learning Confusion matrix is a simple table used to measure how well a classification model is performing. It compares the predictions made by the model with the actual results and shows where the model was right or wrong. This helps you understand where the model is making mistakes so you can improve it. It
8 min read
Top 10 Projects For Beginners To Practice HTML and CSS Skills Learning to code is an exciting journey, especially when stepping into the world of programming with HTML and CSSâthe foundation of every website you see today. For most beginners, these two building blocks are the perfect starting point to explore the creative side of web development, designing vis
8 min read
GATE 2025 Syllabus For CSE (Computer Science & Engineering) GATE Exam 2025 Syllabus for CSE - GATE stands for Graduate Aptitude Test in Engineering, an entrance exam conducted each year for getting admission into the most prestigious institutes across the country including IISc Bengaluru, IITs, NITs, IIITs and many others. The GATE authority (IIT Roorkee for
7 min read
What is Docker? Have you ever wondered about the reason for creating Docker Containers in the market? Before Docker, there was a big issue faced by most developers whenever they created any code that code was working on that developer computer, but when they try to run that particular code on the server, that code
12 min read
HTTP Full Form - Hypertext Transfer Protocol HTTP stands for Hypertext Transfer Protocol, and itâs the system that allows communication between web browsers (like Google Chrome or Firefox) and websites. When you visit a website, your browser uses HTTP to send a request to the server hosting that site, and the server sends back the data needed
7 min read
System Design Interview Questions and Answers [2025] In the hiring procedure, system design interviews play a significant role for many tech businesses, particularly those that develop large, reliable software systems. In order to satisfy requirements like scalability, reliability, performance, and maintainability, an extensive plan for the system's a
7 min read