Use of Let, Var and Const on JS

Use of Let, Var and Const on JS

We use Var keyword in declaring the variable and the scope of the variable is either global or local. The scope of the variable is global if we declare the variable outside of a function otherwise local if declare the variable inside a function. Like this:

                        <script>

                                    var a=10;

                                    var a=100;

                                    function demo ()

                                    {

                                                var a=20;

                                                console.log (“value of local variable a is = ” + a);

                                    }

                                    console.log (“value of global variable a is = ” + a);

                                    demo ();

                        </script>

ES6 use the let keyword for declaring a variable and this is similar to the Var keyword, except that these variables are blocked-scope and we can’t declare the let same variable again. If we declare then its shows Syntax Error: redeclaration of let for this, we use

                        <script>

                                    let a=10;

                                    a=100;

                        </script>

var and let both are used for declaring the variable in JavaScript with a minor difference between them. var is function scoped and let is block scoped.

                        <script>

                        function varDemo () {

                          var x = 10;

                          {

                                    var x = 20; // same variable!

                                    console.log(x); // 20

                          }

                          console.log(x); // 20

                        }

                        varDemo ();

                        function letDemo () {

                          let x = 10;

                          {

                                    let x = 20; // different variable

                                    console.log(x); // 20

                          }

                          console.log(x); // 10

                        }

                        letDemo ();

The const keyword is used for constant fixed value that never be changed i.e. a read-only reference to a value.

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*