DEV Community

Cover image for Understanding JavaScript Variables: const vs let vs var
vasyldubno
vasyldubno

Posted on

Understanding JavaScript Variables: const vs let vs var

In this post, we will delve into the distinctions between const, let, and var, exploring their scopes, hoisting mechanisms, and rules regarding reassignment.

Scope

  • var is function-scoped, meaning it is only accessible within the function it is declared.
  • let and const are block-scoped, meaning they are only accessible within the block (enclosed by curly braces) where they are defined.

Hoisting

  • Variables declared with var are hoisted to the top of their scope, which means they can be used before they are declared. However, the value assigned to them is not hoisted.
  • Variables declared with let and const are also hoisted, but they are not initialized until the point in the code where they are declared. Attempting to access them before the declaration results in a ReferenceError.

Reassignment

  • Variables declared with const cannot be reassigned after they are initialized. They are meant for constant values.
  • Variables declared with let can be reassigned.
  • Variables declared with var can also be reassigned.

Top comments (0)