Block scope
Earlier JavaScript had only Global Scope and Function Scope. let and const are the two new important keywords that were introduced by the ES6 and these two keywords provide Block Scope in JavaScript. ECMAScript (ES6) 2015 was the second major revision to JavaScript. Variables that are declared inside a { } block cannot be accessed from outside the block.
Example: Below is the example of let keyword.
{
let x = 2;
}
x cannot be used here
Example: Below is the example of var keyword.
{
var x = 2;
}
x can be used here
Variables declared with the var keyword cannot have block scope and they can be declared inside a { } block and can be accessed from outside the block.
Example: Below is an example of Block scope.
Javascript
function foo() { if ( true ) { var x = '1' ; // Exist in function scope const y = '2' ; // Exist in block scope let z = '3' ; // Exist in block scope } console.log(x); console.log(y); console.log(z); }foo(); |
Output (In Console):
1
y is not defined
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 flexible way, as the values they hold can change during the execution of a program.
Table of Content
- Variable Scope
- Block scope
- Function scope
- Local scope
- Global scope
In JavaScript, you can declare variables using the var
, let
, or const
keywords. Here’s a brief overview of each:
Variable Declaration |
Description |
---|---|
The oldest way to declare variables. It has function scope and is hoisted. |
|
Introduced in ECMAScript 6 (ES6). It has block scope and is also hoisted. |
|
Also introduced in ES6. It is used to declare constants and has block scope. Unlike |
Now, let’s delve into the concept of Variable Scope in JavaScript:
Contact Us