JavaScript - Variables

Overview

Estimated time: 15–25 minutes

Variables store values for later use. In modern JavaScript, prefer let and const over var.

Learning Objectives

  • Declare variables and initialize values.
  • Choose between let and const.
  • Follow clear naming and scoping conventions.

Prerequisites

Declaring variables

let count = 0;       // changeable
const pi = 3.14159;  // constant binding
// Avoid var in modern code (function-scoped, hoisted)

Naming

  • Use letters, digits, _, $; cannot start with a digit.
  • Use camelCase for variables and functions; PascalCase for classes.
  • Be descriptive: userCount, totalPrice.

Initialization and reassignment

let total = 10;
total = total + 5;  // ok

const max = 100;
// max = 200; // TypeError: Assignment to constant variable.

Common Pitfalls

  • Using var leads to function-scoped variables and hoisting surprises.
  • Reassigning const bindings throws; for objects, the binding is constant but contents can mutate.

Checks for Understanding

  1. When should you choose const?
  2. Is let block-scoped or function-scoped?
Show answers
  1. Default to const for bindings that won’t be reassigned.
  2. let is block-scoped.

Exercises

  1. Refactor a snippet using var to use let/const appropriately; explain your choices.
  2. Create a constant object and mutate one of its properties; explain why this is allowed.