Skip to main content

ES6 Lesson1->Let and Const



Let and Const

In javaSctipt earlier we were using var which is a functional or global scope. Now in Es6 We have new way to assign variable which are let and const which are block scop or local scope.

  1. Let Variable: Let is a block scope varibale whose value can be changed.
  2. Const Variable:Const is a block scoper variable whose value can not changed

What is function/global scope and block scope?

Function scope work on the entire code whereas block level code works inside only a perticular block in which the variable is written. Because of this the error will be less as we can use the same variable multiple times and assign new value without disturbing the earlier ones.

For Expample
    
        in this function scope code we will see the how var works

        var name = "shivam";
        if(name.typeof= string){
            var name = "Neha";
            console.log("i am"+ name);
        } 
        console.log("i am"+ name);

        Output: 
        i amNeha
        i amNeha

        note: As we can see that we have change the assigned value inside the block but the output is same as it updated the local as well as globla scope at the same time.
    
    
        In this example we will see how const and let works
        
            let name = "shivam";
        if(name.typeof= string){
            let name = "Neha";
            console.log("i am"+ name);
        } 
        console.log("i am"+ name);

        Output: 
        i amNeha
        i amShivam

        note: As we can see that we have change the assigned value inside the block but the output is different as the let in inside block did not updated the globla scope.
 
        
    
        In this example we will see how const and let works
        
            const name = "shivam";
        if(name.typeof= string){
            const name = "Neha";
            console.log("i am"+ name);
        } 
        console.log("i am"+ name);

        Output: 
        i amNeha
        i amShivam

        note: As we can see that we have change the assigned value inside the block but the output is different as the const in inside block did not updated the globla scope.
        Also in const we can not update the data for the same variable but here we have done that. As they both have different scope level in the code.
 
        
    

Comments

Popular posts from this blog

ES Introduction

  Introduction TO ECMAScript 2015/ES6. javaSctipt Was created in 1996. it was calles lifescript as it turns the webpage alive. later on in 1997 the javaSctipy was submites to ECMA international or standarlization which resulted in ECMAScript. in 2015 ES6 launched which become famous. ES6 topics Let & Const Template String Arrow Function DeStructuring Object Props Default Arguments Array in ES6 New Number Method New Global Method