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:
Temporal Dead Zone in JavaScript
Next article icon

Lexical Scope in JavaScript

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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. Unlike dynamic scope, which depends on how functions are called at runtime, lexical scope is static and remains the same throughout the program's execution.

What is Lexical Scope?

Lexical scope defines the accessibility of variables and functions depending on their location in the source code. Variables and functions have different levels of scope:

  • Global Scope: Variables defined outside any function or block, accessible anywhere in the program.
  • Local Scope: Variables defined inside a function or block, accessible only within that specific function or block.
  • Nested Scope: Inner functions have access to variables in their parent functions.
  • Block Scope: Variables defined with let and const are limited to the block they are declared in, like loops or conditionals.

In this article, we'll explore lexical scope in JavaScript with different code examples provided to illustrate how it works.

Global Scope

When a variable is defined outside of any functions or blocks, it has a global scope. This means that it can be accessed from anywhere within the program, including within functions.

Example: In the example above, the variable name is defined outside of any functions or blocks, making it a global variable. The function sayHello is then able to access the name variable and output "Hello John" to the console.

JavaScript
let name = "John"; // Global variable  function sayHello() {       console.log("Hello " + name); }  sayHello(); // Output: "Hello John" 

Output
Hello John

Local Scope

When a variable is defined within a function or block, it has a local scope. This means that it can only be accessed within that function or block.

Example: In this example, name is a local variable within sayHello. It’s accessible inside the function, but attempting to access it outside results in a "ReferenceError.

JavaScript
function sayHello() {       let name = "John"; // Local variable          console.log("Hello " + name); }  sayHello(); // Output: "Hello John"  console.log(name);  // Output: Uncaught ReferenceError: name is not defined 

Output:

 

Nested Scope

When a function is defined within another function, it has access to variables defined in the parent function. This is known as nested scope.

Example: In the example above, the function inner is defined within the outer function. The inner function is able to access the name variable defined in the parent outer function, outputting "Hello John" to the console.

JavaScript
function outer() {     let name = "John"; // Outer function variable      function inner() {         console.log("Hello " + name);     }      inner(); // Output: "Hello John" }  outer(); 

Output
Hello John

Block Scope

ES6 introduced the let and const keywords, which allow variables to have block scope. This means that variables defined within a block of code (such as within an if statement or a for loop) can only be accessed within that block.

Example: In this example, message is a block-scoped variable. It's accessible within the if block, but accessing it outside results in a "ReferenceError.

JavaScript
function sayHello() {     let name = "John"; // Function variable      if (true) {         let message = "Hello"; // Block variable         console.log(message + " " + name);          // Output: "Hello John"     }      console.log(message);      // Output: Uncaught ReferenceError:      // message is not defined }  sayHello(); 

Output: 

Conclusion

In JavaScript, understanding lexical scope is essential for writing clean, maintainable code. By properly scoping variables and functions, you can prevent naming conflicts, improve code readability, and avoid unintended side effects. Mastering lexical scope leads to better-organized, more efficient programs.


Next Article
Temporal Dead Zone in JavaScript

N

nishth7hs8
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-basics
  • JavaScript-Questions

Similar Reads

  • Modular Scope in JavaScript
    Modular scope in JavaScript refers to the practice of creating isolated scopes within modules, ensuring that variables and functions are not exposed globally unless explicitly intended. This approach helps prevent name conflicts and encourages better organization of code. Modules allow you to define
    7 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 In Loop
    The JavaScript for...in loop iterates over the properties of an object. It allows you to access each key or property name of an object. [GFGTABS] JavaScript const car = { make: "Toyota", model: "Corolla", year: 2020 }; for (let key in car) { console.log(`${key}: ${car[key]}`); }
    3 min read
  • JavaScript in Operator
    JavaScript in operator is an inbuilt operator which is used to check whether a particular property exists in an object or not. It returns a boolean value true if the specified property is in an object, otherwise, it returns false. Syntax:prop in objectParameters: prop: This parameter holds the strin
    2 min read
  • Temporal Dead Zone in JavaScript
    The Temporal Dead Zone refers to the period between the entering of a scope and the actual declaration of a variable using let or const. During this period, the variable is in an "uninitialized" state and accessing it will result in a ReferenceError. The TDZ starts from the beginning of the block un
    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
  • Namespacing in JavaScript
    Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts. Using namespaces in such a scenario will isola
    2 min read
  • JavaScript Variables
    Variables in JavaScript can be declared using var, let, or const. JavaScript is dynamically typed, so variable types are determined at runtime without explicit type definitions. JavaScript var keywordJavaScript let keywordJavaScript const keyword [GFGTABS] JavaScript var a = 10 // Old style let b =
    5 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 | Namespace
    Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts. Using namespaces in such a scenario will isola
    1 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