DEV Community

Rahul Barwal
Rahul Barwal

Posted on

Variable declarations in JS

there are 3 explicit ways a variable can be declared in javascript.

  1. var
  2. let
  3. const

var

var is the grandfather of declarations in js. important points to know about var:

  • var is hoisted(declaration is brought to the top of function).
    in below example b is available in line#3(albeit undefined) even though it gets declared in line#4

    function myfn() {
        var a =20;
        console.log(a, b); // 20, undefined
        var b= 10;
        console.log(a, b); // 20, 10 ​
    }
    
  • var variables are bound to enclosing function scope(or global).

tricky case

take a look at following case

function fn1() {
    function inner(b) {
      var i=2;
      console.log(b+i);
    }
    for(var i=0; i<10; i++) {
       inner(i);
    }
}
Enter fullscreen mode Exit fullscreen mode

putting your declarations closest to the usage makes sence. but here reusing i will make the for loop run infinitely.

a simple fix would be to declare i insinde inner with var(as this time it will be scoped to inner and will not spoil enclosing fn1s scope)

function inner(b) {
    var i=2;
    console.log(b+i);
}
Enter fullscreen mode Exit fullscreen mode

let & const

in es6 both let and const were introduced to add block scoping to js.

  • let introduces a new block scope in whichever block(if, for or explicit {} it is declared.

    • if

      function myfn() {
          if(true) {
              let a =20;
          }
          console.log(a); // reference error
      }
      
    • for

      function myfn() {
          for(let i=0; i<5; i++) {
          ....
          }
          console.log(i); // reference error
      }
      
    • explicit block {}

      function myfn() {
      
          { 
              let b= 10;
              ....
          }
          console.log(b); // reference error
      }
      
      
  • all above logic is also applicable for const. main difference is with assignment.

    • what this means is that, once a variable is declared as const you can not change it.

      const a = 1;
      a = 2; // error
      
    • that does not mean that variables themselves can not be updated. if variable type is of array or object you can change the properties.. but can't update the variable assignment.

      const a = [];
      a.push(1); // valid
      a = 1; // invalid. error.
      
      const b = {};
      b.val1 = 1; 
      b.val2 = 2; 
      b = {} //invalid. error
      

conclusion

  • when using var in for loops with closures and can lead to unexpected(weired) behaviors. that in iteself is a subject for another post.
  • let/const are not replacement for var. all have their usecases and one should be aware about when to use which.

Top comments (2)

Collapse
 
tris909 profile image
Tran Minh Tri

In higher development, especially real world jobs. We don't use var at all. In fact, it's a buzz word when you come to interview and use var instead of let and const. I reccommend remove var completely when you have learned ES6. Just because It's a industry standard already.

Like I join the interview with my head of engineering one time to interview a girl. And she is not very familiar with javascript and use var instead of let and const like it's a BUZZ right away there. Eventually we didn't fail her because she use var but we did fail her because her lacking of understanding of javacsript.

Collapse
 
rahulbarwal profile image
Rahul Barwal

Agreed, in my experience as well using let makes sense almost all of the time.
There is only one case in favor of var i.e. to use it when you intentionally want to make a variable scoped to the function instead of any block( better done with let if you ask me)

Still, the purpose of article is to provide a comprehensive view of what all is possible in JS and more importantly tell what are the implications of using each one here.
And as you pointed out it being a buzz word for interview, can lead to some tricky questions, around using var with closures - so always good to have an understanding about how it behaves and why it does so.