Skip to main content

let keyword in javascript

let keyword is introduced in 2015(ES6). It is similar to var scope, and it allows the variable’s value to be changed during the course of the program execution.

Let in JavaScript

The let statement allows you to create/declared a block-scoped variable. Block-scoped means whenever a variable is created with let, it will only exist within its block(pair of curly braces).

It is similar to the variable we declare in other languages like : .NET, Java, etc.

# Declaring JavaScript let Variables:

Syntax :

Let’s see the syntax of let keyword :

 ➤ Syntax :

<script>
    let variable_name = value;
</script>
Parameter :
  • let : JavaScript reserved keyword.

  • var_name : Name of constant variable

  • value : ptional, Initial value assign at the time of declaration.


Let’s see an example of let keyword in JavaScript :

 ➤ Example :

<script>
    function display() {
       let a =10;
       console.log(a);   //Output : 10
       if(true) {
          let a=20;
          console.log(a); //Output : 20
        }
        console.log(a);  //Output : 10
     }  
    display();     
</script>

# Scope of let keyword :

1.) Global scope :

  • Using let keyword to define variable globally. Once you define globally, and access anywhere inside your code.

 ➤ Example : Variable scope globally;

<script type="application/javascript; version=1.7">
    let x=1; //'x' is gloabal variable;
     console.log("Start program :",x);
    function display()
     {
        for(x= 1; x< 5; x++) {
          console.log("Looping time :",x); //x visible 
         }
         console.log("Inside function :",x); //x visible
     }
     display(); //calling JavaScript function
     console.log("End program :",x); //x visible
</script>

2.) Local scope :

  • Using let keyword to define variable locally (local scope). It can't be accessed or modified outside the function declaration.

 ➤ Example : Variable scope within function;

<script type="application/javascript; version=1.7">
   function display()
     {
       let a =10;
       console.log("Inside function : "+a); //Inside function :10
     }
     display();
    //ReferenceError: a is not defined
     console.log("outside function : "+a);
</script>

3.) Block scope :

  • Variables declared with let keyword inside a block { } , can't be accessed from outside the block. When you try to access from outside of block, It will get a ReferenceError.

 ➤ Example : variable scope within block;

<script type="application/javascript; version=1.7">
  let age = 22;
  if (age > 21)
    {
      let message ="Hello";
      console.log("Inside block, message : ",message); //Hello!
    }
    //ReferenceError: message is not defined
    console.log("Outside block : ",message);
</script>

# Variable Hoisting :

Unlike var keyword, The variable declared using ‘let’ keyword is not hoisted. So if you try to use the variable before declaring it, javascript throw a Reference Error.

Let's try to create an exaple :

 ➤ Example :Variable hoisting with let;

    Variables declared with let are not hoisted to the top.

<script>
    console.log(name); //ReferenceError
    let name = "Ankaj";
</script>

 ➤ Read more :

Read more about Variable Hoisting : Click Me



Important point's of let keyword in JavaScript :

  • Variable access befor declaration : let variables are registered at the top of the block, But when the variable is accessed before declaration, JavaScript throws a ReferenceError.

 ➤ Example:

    let can't use variable before the declaration otherwise gives an error.

<script>
    document.write(x); //ReferenceError: x is not defined
</script>
  • Variable use without initialization : The let statement creates and initializes variables inside the block scope. If you don't assign variables value at declaration time, By default JavaScript automatically a declared assigns the undefined value.

 ➤ Example:

    A variable declared without a value will have the value undefined.

<script>
    let name;
    document.write(name); //undefined
</script>
  • Block-scope : Variables declared with let keyword inside a block { } , can't be accessed from outside the block. When you try to access from outside of block, It will get a ReferenceError.

 ➤ Example :

    Variables declared with the let keyword have Block Scope.

<script>
    for(let i=0; i<=5; i++ )
    {
      //write something
    }
    document.write(i); //ReferenceError: i is not defined
</script>
  • Variable Re-declaration : Unlike var, You can't declare the same variable more than one time using ‘let’ keyword within the same scope. When we try to redefine, It will get a SyntaxError.

 ➤ Example : variable re-declaration in same scope;

    Variables defined with let keywords can't be redeclared in the same scope.

<script>
    let a = 10; 
    let a = 20; //SyntaxError: Identifier 'a' has already been declared
</script>

 ➤ Example : variable re-declaration in separate scope;

    Variables defined with let keywords can be redeclared in the separate scope.

<script>
    let a = 10; //Global scope
    function display()
    {
      let a= 20; //Local scope
    }
    if(true)
    {
      let a= 25; //Block scope
      display();
    }
</script>
  • Variable value re-assigned : Variable data store in memory, which can later be accessed and modified (reassigned a new value).

 ➤ Example : Assigned a new value in given variable;

<script>
    // Assign value to x variable
    let x=10;
    //Reassign variable with a new value
    x = 20;
    console.log(x); //Output : 20
</script>
  • Dynamic type : Variables declared with let keyword are dynamic typing mean that, they can change from one data type to another data type.

 ➤ Example : Dynamic type variables;

    In this example, the variable myName change from string to number and then boolean.

<script>
    let myName = 'Ankaj Gupta';  //Ankaj Gupta
    myName= 100; //100
    myName= true; //true
</script>

Comments

Popular Posts

Django static files not working when debug false || debug true

# Django static and media files not working when debug is false In this article you will learn how to fix problem of not loading static files and media in Django even the DEBUG is FALSE. This is the easiest and safest solution. # Problem: Django static and media files not working when debug is false  ➤ Code: settings.py DEBUG = False #True ALLOWED_HOSTS = [ '*' ] #Host name # Problem Fix: Let's see, How you can fix the problem of Django static and media files not working when DEBUB = False : 1.)First way: devserver in insecure mode If you still need to server static locally ( e.g. for testing without debug ) you can run devserver in insecure mode: python manage.py runserver --insecure --insecure: it means you can run serve...

How to remove the date and .html from every blogger post url

#Remove date and .html from blogger post url A Common search term which every blogger search is How to Remove Date From Blogger Post URL or how do I remove date from blogger permalink? Follow the steps below and then date and .html will be removed from the URL of your blogger post. Step 1 : Login to your Blogger blog and select Theme / Template. Step 2 : Click on Edit HTML and paste the below code just above the </head> tag let's see code :   ➤ Code : mycode.js; Copy code <script type='text/javascript' > //<![CDATA[ // BloggerJS v0.3.1 var urlTotal,nextPageToken,postsDatePrefix=!1,accessOnly=!1,useApiV3=!1,apiKey="",blogId="",postsOrPages=["pages","posts"],jsonIndex=1,secondRequest=!0,feedPriority=0,amp="&"[0];function urlVal(){var e=window.location.pathname,t=e.length;return...

How to remove ? m=1 or ?m=0 from blogger post URL

# Remove m=1 From URL of Blogger post A Common search term that every blogger search is How to ?m=1 or ?m=0 from blogger Post URL. We all know that "simplicity is beauty" and you want to clean permalink. So, in this article, I will guide you on how to remove ?m=1 from the blogger URL, and make a simple professional URL. Follow the few steps below and removed ?m=1 from the URL of your blogger post. Step 1 : First, you login into your blogger's dashboard and then select your blog. Step 2 : Click on the Theme option. Step 3 : Click on the customise Step 4 : Click on Edit HTML option. Step 5 : Press (CTRL + F) from the keyboard and type "/head" and then search. ( If you are not understanding, see the below photo ) Step 6 : Now paste the below code just above the </head> tag. let's see code :   ➤ Code : mycode.js; Copy code ...