DEV Community

Arthur
Arthur

Posted on

JavaScript Variables

var

  • Old way of declaring variables
  • Scope is function-based (not limited to blocks)
  • Can be changed later
  • Can be redeclared in the same scope
  • Less safe and can lead to unexpected behavior

let

  • Modern way to declare variables
  • Scope is block-based
  • Value can be changed (reassigned)
  • Cannot be redeclared in the same scope
  • Safer and more predictable than var

const

  • Modern way for fixed values
  • Scope is block-based
  • Value cannot be changed or reassigned
  • Must be initialized when declared
  • Used for values that should stay constant

Scope (where variables exist)

  • var → function scope
  • let and const → block scope

Hoisting (simple idea)

  • var is available before declaration but has an empty value initially
  • let and const are also known before declaration but cannot be used before they are defined

JavaScript Modes

Sloppy Mode

  • Default mode
  • Less strict rules
  • Allows unsafe or accidental behaviors

Strict Mode

  • Activated manually
  • Prevents many common mistakes
  • Safer and recommended for real projects

Top comments (0)