DEV Community

Rabe Datta
Rabe Datta

Posted on • Edited on

var vs let & const.

Redeclaration of variable

You can redeclare a variable with var, but not with let and const:

var foo = 34;
var foo = 46;

foo; // 46
Enter fullscreen mode Exit fullscreen mode

However, if we try to redeclare a variable with const and let, we will get a syntax error:

var foo = 34; 
let  foo =46;

foo;  
// SyntaxError: Identifier 'foo' has already been declared.
Enter fullscreen mode Exit fullscreen mode

Global scope & function scope vs block scope

var only has knowledge of global scope and function scope. This means that if you declare a var variable inside an if statement, you can still access it from outside of that if statement. However, you can't do the same with let and const. For example:

var name = "Max"; 

if(name === 'Max'){
  var hobbies = ['Sports', 'Cooking']; 
  console.log(hobbies)  // [ 'Sports', 'Cooking' ]
}

console.log(name, hobbies)  
// 'Max' [ 'Sports', 'Cooking' ]
Enter fullscreen mode Exit fullscreen mode

Notice that you can still access hobbies from outside of the if block. But in the case of let and const, we can't do that since both let and const are block-scoped.

var name = "Max"; 

if(name === 'Max'){
  let hobbies = ['Sports', 'Cooking']; 
  console.log(hobbies)  // [ 'Sports', 'Cooking' ]
}


console.log(name, hobbies) 
// ReferenceError: hobbies is not defined

Enter fullscreen mode Exit fullscreen mode

As you can see, we get a ReferenceError. let and const only care about curly braces (except for curly braces of an object). You can't access a variable defined inside a child block from outside. Also, you can't access a variable that you defined inside a nested block.


var name = "Max"; 

if(name){
  {
    let test = 34;
  }

console.log(test)  
// ReferenceError: test is not defined
}

Enter fullscreen mode Exit fullscreen mode

Hoisting: var vs let & cost

When it comes to var, JavaScript initializes the hoisted variable as undefined:

console.log(name); //'undefined'

var name = "Rob"
Enter fullscreen mode Exit fullscreen mode

When it comes to let and const, the declarations remain uninitialized:

console.log(name);        // ReferenceError: 

//Cannot access 'name' before initialization

var name = "Rob"
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
ravavyr profile image
Ravavyr

Use object.freeze around your consts otherwise if they have sub arrays or objects those can still be modified, at which point it shouldn't be a const anyway.

Everything changes eventually, i just "let" it all.

Collapse
 
lico profile image
SeongKuk Han

I didn't know that there is a term about that. Thank you

Collapse
 
pulimoodan profile image
Akbar Ali

Note: You cannot change the value of a cost variable after declaration.

Collapse
 
rabedatta profile image
Rabe Datta

Yep.
The property of a const object can be change and values inside the const array can be change as well. But you can't reassigned them.