Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Variable Shadowing in JavaScript
Next article icon

Understanding Variable Scopes in JavaScript

Last Updated : 16 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, scope defines the accessibility of variables in different parts of your code. It determines where a variable can be accessed or modified.

  • Before ES6 (Released in 2015), variables were declared only with var, which is function-scoped (accessible within the function) and global Scoped (Accessible everywhere) and prone to issues like hoisting and global pollution.
  • let and const were introduced with ES6. Variables declared with let and const are either block scoped or global-scooped.

Types of Scope

  1. Global Scope: Variables declared outside any function or block are accessible everywhere in the code.
  2. Function Scope: Variables declared with var inside a function are accessible only within that function. Function can be nested in JavaScript and the inner function can access outer function members and this is called Lexical Scope.
  3. Block Scope: Variables declared with let or const inside a block ({}) are accessible only within that block.
  4. Modular Scope: Introduced in ES6, ES Modules are the standard way to organize JavaScript code into reusable and maintainable chunks. Each module has its own scope, and anything declared within a module is private by default unless explicitly exported.

Example of Global Scope

JavaScript
// Using var var x = 10; console.log(x);  // Using let let y = 20; console.log(y);   // Using const const z = 30; console.log(z);  

Output
10 20 30 

Note: Here let and const are behaving similar to var but they do not attach to the window object. They are scoped globally but are not properties of window, making them safer and less prone to conflicts.

JavaScript
var globalVar = "I am global"; console.log(window.globalVar);   let globalLet = "I am block-scoped"; console.log(window.globalLet); 
global-scope-of-let

Understanding variable scopes in JavaScript

Examples of Block Scope

JavaScript
if (true) {     var x = 10;   // Function-scoped (not block-scoped)     let y = 20;   // Block-scoped     const z = 30; // Block-scoped }  console.log(x); // Output: 10 (accessible outside the block) console.log(y); // Error: y is not defined (block-scoped) console.log(z); // Error: z is not defined (block-scoped) 

Example of Function Scope

JavaScript
function example() {     var x = 10;   // Function-scoped     let y = 20;   // Function-scoped     const z = 30; // Function-scoped     console.log(x, y, z); // Output: 10 20 30 }  example();  console.log(x); // Error: x is not defined console.log(y); // Error: y is not defined console.log(z); // Error: z is not defined 


Example of Modular Scope

Math.Js
const PI = 3.14; function add(a, b) {   return a + b; }  module.exports = { PI, add }; 
App.Js
const { PI, add } = require('./math');  console.log(PI);        // 3.14 console.log(add(2, 3)); // 5 

Lexical Scope (Closures)

Lexical scope means a function can access variables from its outer scope even after the outer function has finished execution.

JavaScript
function outer() {     let outerVar = "I'm in the outer scope!";     function inner() {         console.log(outerVar); // Accessing parent's scope     }     inner(); } outer(); 


Different cases of scope

We have a global variable defined in the first line in the global scope. Then we have a local variable defined inside the function fun(). 

javascript
let globalLet = "This is a global variable"; {     let localLet = "This is a local variable";      // This is a global variable     console.log(globalLet);          // This is a local variable     console.log(localLet);    } 

Output
This is a global variable This is a local variable 
  • Global Variables: Inside a function, global variables (declared outside) are accessible.
  • Local Variables: Local variables (declared inside the function) are also accessible within that function.

Let’s move the console.log statements outside the function and put them just after calling the function. 

javascript
let globalLet = "This is a global variable"  function fun() {     let localLet = "This is a local variable"  } fun(); console.log(globalLet); console.log(localLet); 
  • Global Variable: globalLet is accessible outside the function since it’s declared in the global scope.
  • Local Variable: localLet is not accessible outside the function, causing an error, as it’s scoped only within the function.

Word of caution: Whenever you are declaring variables, always use the prefix let. If you don’t use the let keyword, then the variables are by default created in the global scope. For instance, in the above example.

let’s just remove the keyword let before the declaration of localLet. 

javascript
let globalLet = "This is a global variable";;  function fun() {     localLet = "This is a local variable"; }  fun(); console.log(globalLet); // This is a global variable console.log(localLet); // This is a local variable 

Output
This is a global variable This is a local variable 
  • Global Variable: globalLet remains accessible as it is declared in the global scope.
  • Implicit Global Variable: Without the let keyword, localLet is treated as a global variable, even though it was intended to be local to the function.

One of the most asked questions in interviews is the case where the global as well as local variable has the same name. Let’s see what happens then. 

javascript
let globalLet = "This is a global variable"  function fun() {     let globalLet = "This is a local variable" } fun(); console.log(globalLet); // This is a global variable 

Output
This is a global variable 
  • Local Variable: Inside the function, globalLet is re-declared as a local variable, but it does not affect the global globalLet because of the function scope.
  • Global Variable: The global globalLet remains unchanged and accessible outside the function, so console.log(globalLet) outputs the global value.

Let’s move the console.log statement inside the function fun(). 

javascript
let globalLet = "This is a global variable";  function fun() {     let globalLet = "This is a local variable";     console.log(globalLet); } fun(); 

Output
This is a local variable 
  • Local Variable Preference: Inside the function, JavaScript first looks for globalLet in the local scope, finds it, and logs the local variable.
  • Scope Search: If globalLet weren’t declared locally, JavaScript would search for it in the global scope.

What if we want to access the global variable instead of the local one here? Well, the window object comes to our rescue. All the global variables declared using the “var” keyword or without using any keyword are attached to the window object and thus we can access the global variable name as shown in the example below. 

javascript
let globalLet = "This is a global variable";  function fun() {     let globalLet = "This is a local variable";     console.log(window.globalLet); // This is a global variable } fun(); 

Output:



Next Article
Variable Shadowing in JavaScript
author
kartik
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-basics

Similar Reads

  • Variable Shadowing in JavaScript
    Variable Shadowing in JavaScript occurs when the inner variable hides or overrides the outer variable within the local scope. In this situation, the outer variable cannot be accessed within the inner scope, only the inner variable is used in that scope. Variable Shadowing occurs when we declare the
    4 min read
  • Understanding the Async in JavaScript
    Definition: Async is a short form for “asynchronous”. Synchronous means executing statements one after the other which implies the next statement will get executed only after the previous statement is executed completely. Whereas in Asynchronous calls the next statement gets executed without even wa
    4 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
  • Scope : Variable Masking in JavaScript
    In this article, we will learn about Variable Masking which is also known as Variable Shadowing i.e. a variable with the same name will shadow the variable in the outer scope. When a variable is masked, the masked variable is completely inaccessible using that variable name. The scope is hierarchica
    3 min read
  • Shadowing Properties in JavaScript
    Shadowing properties in JavaScript refer to the scenario where a variable declared within a nested scope has the same name as a variable in its outer scope. This can lead to confusion and unexpected behaviour, as the inner variable may "shadow" the outer one, effectively hiding it from the outer sco
    2 min read
  • variable === undefined vs. typeof variable === “undefined” in JavaScript
    Undefined comes into the picture when any variable is defined already but not has been assigned any value. Undefined is not a keyword. A function can also be undefined when it doesn't have the value returned. There are two ways to determine if a variable is not defined, Value and type. var geeks; al
    2 min read
  • JavaScript Local Variables
    What are Local Variables in JavaScript?JavaScript local variables are declared inside a block ({} curly braces) or a function. Local variables are accessible inside the block or the function only where they are declared. Local variables with the same name can be used in different functions or blocks
    2 min read
  • JavaScript Course Variables in JavaScript
    Variables in JavaScript are containers that hold reusable data. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory loca
    4 min read
  • What are undeclared and undefined variables in JavaScript?
    Undefined: It occurs when a variable has been declared but has not been assigned any value. Undefined is not a keyword. Undeclared: It occurs when we try to access any variable that is not initialized or declared earlier using the var or const keyword. If we use 'typeof' operator to get the value of
    1 min read
  • Reference and Copy Variables in JavaScript
    In this article, we will talk about pass-by-value and pass-by-reference in JavaScript. JavaScript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the data. JavaScript has 5 primitive data types that are passed by value, they are Boolean, NULL, u
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences