DEV Community

Khafido Ilzam
Khafido Ilzam

Posted on

JavaScript Declaration Variable

In JavaScript, variables are declared using one of three keywords: var, let, or const. These keywords differ in their scope, hoisting behavior, and re-assignment rules.

1. var – the old way (avoid using it)

  • Function-scoped → only respects function boundaries.
  • Can be re-declared.
  • Can be updated.
  • Hoisted → moved to the top of the scope, but initialized as undefined.

It can cause weird bugs because it ignores block scope.

var x = 1;
if (true) {
  var x = 2;  // same variable!
}
console.log(x); // 2
Enter fullscreen mode Exit fullscreen mode

2. let – recommended for variables that change

  • Block-scoped → respects { } blocks.
  • Can be updated, but not re-declared in the same scope.
  • Also hoisted, but not usable before declared (“temporal dead zone”).

Use let when the value needs to change.

let count = 1;
count = 2; // OK
// let count = 3; // ❌ Error (same scope)
Enter fullscreen mode Exit fullscreen mode

3. const – recommended default

  • Block-scoped
  • Cannot be updated or re-declared
  • Best for values that should not change

Objects and arrays can still be modified, but the variable reference cannot change.

const PI = 3.14;
// PI = 4; // ❌ Error

const user = { name: "Khaf" };
user.name = "Fido"; // ✔ OK
// user = {} // ❌ Not allowed
Enter fullscreen mode Exit fullscreen mode

Summary

Feature var let const
Scope Function Block Block
Re-declare ✔ Yes ❌ No ❌ No
Update value ✔ Yes ✔ Yes ❌ No
Hoisted Yes (weird) Yes (safer) Yes (safer)
When to use Avoid Value changes Value doesn't change

Top comments (0)