JavaScript variables

JavaScript Variables can be declared in 4 ways:

  • Automatically
  • var
  • let
  • const

1. Automatically

They are automatically declared when first used:

x = 5;
y = 6;
z = x + y; // Output: 11

2.var

  • Scope: Function-scoped or globally scoped if declared outside any function.
  • Re-declaration: Allows re-declaration within the same scope, which can lead to unexpected behavior.
  • Hoisting: Variables declared with var are hoisted to the top of their scope (but only their declaration, not their initialization).

Example:

var name = "Alice";
var name = "Bob"; // No error, allowed in the same scope

3. let

  • Scope: Block-scoped, meaning it’s only accessible within the { } it was defined in.
  • Re-declaration: Cannot be re-declared within the same scope, helping to avoid errors.
  • Hoisting: let variables are also hoisted, but unlike var, they are not initialized. They enter a “temporal dead zone” from the start of the block until their declaration, which prevents access before they are declared.

Example:

let age = 25;
let age = 30; // Error: can't re-declare in the same scope

3. const

  • Scope: Block-scoped, similar to let.
  • Re-declaration: Cannot be re-declared or reassigned within the same scope.
  • Initialization: Must be initialized at the time of declaration, as it cannot be assigned later.
  • Immutability: The variable itself is immutable (i.e., it can’t be reassigned), but if it’s an object or array, the properties or elements inside can be modified.

Example:

const city = "New York";
city = "Los Angeles"; // Error: cannot reassign a `const` variable

Summary

KeywordScopeRe-declarationReassignmentHoisting
varFunction / GlobalAllowedAllowedYes (initially undefined)
letBlockNot allowedAllowedYes (in “temporal dead zone”)
constBlockNot allowedNot allowedYes (in “temporal dead zone”)

Leave a Reply

Your email address will not be published. Required fields are marked *