Variables and Hoisting - var, let and const

    Variable is a container which stores some value into it. The names of the variables are called identifiers.

There are certain rules you have to follow while declaring a variable name:

       A JavaScript identifier starts with a letter, underscore( _ ) or a dollar sign($). It cannot start with a digit or other special character.

You can declare a variable in three ways:

       1. var 
                The var keyword declares a globally scoped variable.

        Example:

                  var a = 100
                  if(a===100){
                         var a ="hello world"
                         console.log(a) //output: hello world
                  }
                  console.log(a) //output: hello world

Notice here "hello world" is printed both inside and outside the block, here before if block the type of variable "a" was a number and later it changes to a string. This is because JavaScript is a dynamically typed language.

             Even if you declare the variable like this:

            a = 100
                  if(a===100){
                         var a ="hello world"
                         console.log(a) //output: hello world
                  }
                  console.log(a) //output: hello world

           It still prints the same output even we have declared the variable later before assigning it. This is because var keyword wherever they occur, are processed before any code is executed and their initial value is undefined. This is called hoisting.

Note: duplicate variable declared using var will not throw any error.

       Consider one more example:

        var x=100
        function a(){
             var x=2 //declares in function scope
             var y = 10 //declares in function scope
              console.log(x,y) //output: 2,10
       }
       a()
      console.log(x) //output: 100
      console.log(y) //ReferenceError: y is not defined

       Since variable declared within function scope will exist only until function is running.


       2. let  
             To handle the hoisting behavior of JavaScript, let is introduced. It declares a block-scoped local variable.  

       Example:

              let x=2
              if(x===2){
                    let x = 4
                    console.log(x) //output: 4
              }
              console.log(x) //output:2

        Note: Accessing the variable before it's initialization will result in an error if you have declared it using let keyword. Also, we cannot redeclare let variable like var variables.

       3. const 
              As like let keyword, const also declares a block-scoped constants. And the value of constant can't be changed, and it can't be declared as well.

       Example:

             const a= 10
             a=15 //TypeError: invalid assignment

 

       Note: const declaration always need an initializer.

Continue Learning: Datatypes in JavaScript

Comments

Popular Posts