What is the difference between var, let, and const?

EasyPhone Screen
AmazonSoftware Development Engineer
189

Explain the differences between var, let, and const in JavaScript. When would you use each one?

1 Answer

212
Top Answer

var

  • Function scoped (or global if declared outside)
  • Hoisted and initialized as undefined
  • Can be redeclared
console.log(x); // undefined (hoisted)
var x = 5;
var x = 10; // OK - redeclaration allowed

let

  • Block scoped (inside {})
  • Hoisted but NOT initialized (temporal dead zone)
  • Cannot be redeclared in same scope
console.log(y); // ReferenceError!
let y = 5;
let y = 10; // SyntaxError!

const

  • Same as let, but cannot be reassigned
  • Must be initialized at declaration
  • Object properties CAN still be modified
const z = 5;
z = 10; // TypeError!

const obj = { a: 1 };
obj.a = 2; // OK - modifying property
obj = {}; // TypeError - reassigning

Best Practice

Use const by default, let when you need to reassign, avoid var.

ModernJS

Share Your Answer

Help others by sharing your knowledge and experience with this question.

Coming soon...

Related Questions

View all

More from Amazon

View all