How to Answer: What is the difference between var and let?
Advice and answer examples written specifically for a Javascript Beginner Level Conceptual Questions job interview.
2. What is the difference between var and let?
This question tests the knowledge of JavaScript variables.
var and let both are used to declare variables in Javascript. The var-variables get hoisted while let-variables are not hoisted. We can not access let-variables before they are declared
The variables assigned using var get hoisted to function scope. These variables declared in inner blocks are accessible outside of the block scope. These variables can also be redeclared.
function f() {
a = 2
console.log(a) // 2
{
var a = 4
console.log(a) // 4
}
{
console.log(b) // undefined because it was hoisted
{
// 2-level nested blocks
var b = 13
var b = 3 // redeclaration- OK
}
console.log(b) // 3
}
console.log(b) // 3
}
console.log(a) // error
console.log(b) // error
c = 1
console.log(c) // 1
{
var c = 11
console.log(c) // 11
}
console.log(c) // 11
But, the variables assigned using let are not hoisted and are block level. They can not be redeclared.
{
console.log(a) // error
let a = 4
let a = 5 // redeclaration- error
}
console.log(a) // error
Written by Jennie Taylor on May 21st, 2021