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:
When should one use Arrow functions in ES6 ?
Next article icon

What are Block Scoped variables and functions in ES6 ?

Last Updated : 10 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Block-scoped variables and functions are defined inside a particular block or inside curly { } braces and they can only be accessible inside that particular block or within that block. The block-scoped variables were first introduced in EcmaScript2015 or es6. ES6 introduces us with two keywords: let and const which allows us to declare variables with block scope. Let us see them in detail in this article.

The let keyword: The let keyword does not allow us to redeclare a variable in the same block, while it is possible when you declare it using the var keyword. If you try to redeclare a variable defined using the let keyword it will throw the error as SyntaxError: Identifier has already been declared.

Syntax:

let first_name="John";

Example 1: The below example illustrates when we are not redeclaring the variable with let keyword.

HTML




<script>
    function myFunction() {
        var name = "GeeksforGeeks";
        let desc =
            "A computer science portal for all geeks";
        console.log(name);
        console.log(desc);
       
        var name = "GFG";
        console.log(name);
 
    }
    myFunction();
    console.log(desc); // ReferenceError: desc is not defined
</script>
 
 

Output:

Without redeclaration

Example 2: The below example illustrates when we are redeclaring the variable with let keyword.

HTML




<script>
    function myFunction() {
        var name = "GeeksforGeeks";
        let desc =
            "A computer science portal for all geeks";
        console.log(name);
        console.log(desc);
       
        var name = "GFG";
        let desc = "Welcome to GFG";
        console.log(name);
        console.log(desc);
    }
    myFunction();
</script>
 
 

Output:

Using redeclaration

The const keyword: The variables declared using const keyword can not be redeclared like let keyword as well as we can not reassign them. We use const keyword to declare a constant whose value we don’t want to change in code. If we try to reassign the const variable it will show an error as TypeError: Assignment to constant variable.

Syntax:

const age = 23;

Example 1: In this example, we try to reassign a const variable resulting in an error.

HTML




<script>
    function myFunction() {
        var name = "GeeksforGeeks";
        const desc = "A computer science portal for all geeks";
        desc = "Welcome to GFG";
        console.log(name);
        console.log(desc);
    }
    myFunction();
</script>
 
 

Output:

Example 2: In this example we try accessing a variable outside the function.

HTML




<script>
    function myFunction() {
        var name = "GeeksforGeeks";
        const desc =
              "A computer science portal for all geeks";
        console.log(name);
        console.log(desc);
    }
    myFunction();
    console.log(desc); //ReferenceError: desc is not defined
</script>
 
 

Output:

Example 3: In this example we try to redeclare the description variable.

HTML




<script>
    function myFunction() {
        var name = "GeeksforGeeks";
        const description =
              "A computer science portal for all geeks";
        console.log(name);
       
        const description = "Welcome to GFG!";
        console.log(description);
    }
    myFunction();
</script>
 
 

Output:

Block-scoped functions: Block-scoped functions can be defined inside the block of code that block could be inside simple curly braces or inside any function of the conditional statement. If a function is written inside another function, then those functions are nested functions.

Function written inside another function:

Syntax:

 function func1(){      // Content of the func1()            function func2(){          // Content of the func2()      }  }

Example:

HTML




<script>
    function myFunction() {
        var name = "GeeksforGeeks";
        function myFunction2() {
            let desc =
                "A computer science portal for all geeks.";
            console.log(name);
            console.log(desc);
        }
        myFunction2();
        console.log(name);
    }
    myFunction();
</script>
 
 

Output:

Function written inside a conditional statement:

Syntax:

if (true){     // Content of conditional statement          function func1(){         // Content of func1()     } }

Example:

HTML




<script>
    if (true) {
        var name = "GeeksforGeeks";
        function myFunction() {
            let description =
                "A computer science portal for all geeks.";
            console.log(name);
            console.log(description);
        }
        myFunction();
    }
</script>
 
 

Output:



Next Article
When should one use Arrow functions in ES6 ?

A

abhisheksainiaggarwal
Improve
Article Tags :
  • Geeks Premier League
  • JavaScript
  • Web Technologies
  • ES6
  • Geeks-Premier-League-2022
  • JavaScript-Questions

Similar Reads

  • What is blocked scoped variables ES6 ?
    In ES5 when we declare a variable with the var keyword, the scope of the variable is either global or local. Global variable: When we declare a variable outside of a function. Local variable: When we declare a variable inside of a function. But, ECMAScript 2015 (ES6) introduced two new keywords let
    4 min read
  • When should one use Arrow functions in ES6 ?
    In this article, we will try to understand when should one use Arrow functions in ES6 instead of the traditional function's syntax with the help of some examples. Before analyzing why we should use arrow functions, let us first understand the basic details which are associated with the arrow functio
    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
  • What is a typical use case for anonymous functions in JavaScript ?
    In this article, we will try to understand what exactly an Anonymous function is, and how we could declare it using the syntax provided in JavaScript further we will see some examples (use-cases) where we can use anonymous functions to get our results in the console. Before proceeding with the examp
    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
  • What is the first class function in JavaScript ?
    First-Class FunctionA programming language is said to have First-class functions if functions in that language are treated like other variables. So the functions can be assigned to any other variable or passed as an argument or can be returned by another function. JavaScript treats function as a fir
    2 min read
  • What is the (function() { } )() construct in JavaScript?
    If you've ever played around with JavaScript, you might have seen this expression. It's like a strange set of symbols, but it has a special name that is an immediately invoked function expression, or IIFE. In this article, we will understand each element of the expression as well as the functionalit
    3 min read
  • What are Arrow/lambda functions in TypeScript ?
    Arrow functions in TypeScript (also known as lambda functions) are concise and lightweight function expressions using the => syntax. Provide a shorter syntax for defining functions.Automatically bind the context of their surrounding scope.It is commonly used for callbacks, array methods, and simp
    3 min read
  • Passing a function as a parameter in JavaScript
    In this article, we will pass a function as a parameter in JavaScript. Passing a function as an argument to the function is quite similar to passing a variable as an argument to the function. So variables can be returned from a function. The below examples describe passing a function as a parameter
    1 min read
  • What are the classes and proxies in JavaScript ?
    Classes: These are almost similar to functions, except they use a class keyword instead of a function keyword. Another important difference between functions and classes is that functions can be called in code before they are defined whereas classes must be defined before a class object is construct
    4 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