What is difference between let and const in javascript?


What is var, let, and const in JavaScript?

var vs let vs const in JavaScript: variable is the container where we can store value. We define with the var keyword. Same as we can define as a variable in ES6 as we know let and const keyword. In simply “we can say that var be a function scope and let and const be a block scope.” 

Block scope means we have to write code in the “{}” (curly braces) this is block scope. If we write any code with variable with var keyword then it is a function scope as below example:


var xyz = 'Sheo'
        function myFuncName() {
            var abc = 'Hello world!';
            console.log(abc); // 'Hello world!'
        }
        myFuncName(); // It will show Hello world!
        console.log(xyz); // It will show Sheo
        console.log(abc); // Uncaught ReferenceError: abc is not defined

Block scope example below:
if(true) {
            var abc = 'Hello world!';
            let letVar = 'Let content';
            const constVar = 'Const content';

            console.log(abc); // It will show Hello world!
            console.log(letVar); // It will show Let content
            console.log(constVar); // It will show Const content
        }

    console.log(abc); // It will show Hello world!
    console.log(letVar); // Uncaught ReferenceError: letVar is not defined
    console.log(constVar); // Uncaught ReferenceError: constVar is not defined

Means you cannot access the value in out of the curly braces because we are using let and const keyword so we can access only with block scope.

See your result below: 




No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.