What is Variable Scope in JavaScript ?
Last Updated :
05 Mar, 2024
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.
In JavaScript, you can declare variables using the var
, let
, or const
keywords. Here's a brief overview of each:
Variable Declaration
| Description
|
---|
var
| The oldest way to declare variables. It has function scope and is hoisted.
|
---|
let
| Introduced in ECMAScript 6 (ES6). It has block scope and is also hoisted.
|
---|
const
| Also introduced in ES6. It is used to declare constants and has block scope. Unlike let , a const variable cannot be reassigned.
|
---|
Now, let's delve into the concept of Variable Scope in JavaScript:
Variable Scope
Variable scope in JavaScript is the region of the code where a particular variable can be accessed or modified.
Types of Scopes in JavaScript:
- Block scope
- Function scope
- Local scope
- Global scope
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
Function scope
JavaScript has function scope and each function creates a new scope. Variables defined inside a function are not accessible from outside the function and variables declared with var, let and const are quite similar when declared inside a function.
Example: Below is an example of var keyword.
function myFunction() {
var firstName = "Krishna"; // Function Scope
}
Example: Below is an example of let keyword.
function myFunction() {
let firstName = "Krishna"; // Function Scope
}
Example: Below is an example of const keyword.
function myFunction() {
const firstName = "Krishna"; // Function Scope
}
Local scope
Variables declared inside a function become local to the function. Local variables are created when a function starts and deleted when the function is executed. Local variables have Function Scope which means that they can only be accessed from within the function.
Example:
// This part of code cannot use firstName
function myFunction() {
let firstName = "Krishna";
// This part of code can use firstName
}
This part of code cannot use firstName
Example: Below is an example of Local scope.
JavaScript
function foo() {
var x = '1';
console.log('inside function: ', x);
}
foo(); // Inside function: 1
console.log(x); // Error: x is not defined
Output (In Console):
inside function: 1
x is not defined
Global scope
Variables declared Globally (outside of any function) have Global Scope and Global variables can be accessed from anywhere in a program. Similar to function scope variables declared with var, let and const are quite similar when declared outside a block.
let keyword:
let x = 2; // Global scope
const keyword:
const x = 2; // Global scope
var keyword:
var x = 2; // Global scope
Example: Below is an example of Global scope.
JavaScript
// Global scope
var x = '1'
const y = '2'
let z = '3'
console.log(x); // 1
console.log(y); // 2
console.log(z); // 3
function getNo() {
console.log(x); // x is accessible here
console.log(y); // y is accessible here
console.log(z); // z is accessible here
}
getNo();
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read