Back to all questions

What is the difference between let and var?

Devs Hive

Devs Hive

Seen on interview: 2 users

This question isn't asked often, but it's still relevant, so it's worth understanding the main differences:

Scope

var has function scope, so if we declare a var variable inside a {} block, it is still visible throughout the function where it was declared, or in the global object's scope.

if (true) {
var a = 10;
let b = 20;
}

console.log(a); // 10
console.log(b); // undefined або помилка, якщо використовується strict mode

function fn() {
var c = 30;
}

console.log(c) // тут буде undefined, так як функція інкапсулює змінну c

Hoisting

In general, both var and let are hoisted to the top of their scope, but there is a significant difference when you try to access them.

var is hoisted and initialized with the value undefined, which is what we get when we access it. let is hoisted too, but trying to access it before the declaration throws an error.

console.log(x); // undefined
var x = 5;

console.log(y); // ReferenceError
let y = 10;

Redeclaration

var can be redeclared within the same scope.

let cannot be redeclared within the same block, because it results in an error.

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!