CCA Prep

Lesson 1.1Lesson 1 of 24

Declaring variables with var, let and const

Given a scenario, write code to create variables and initialize them correctly.

Declaring variables with var, let and constWhich declaration?The variable never pointsto another valueconstobjects inside can stillchangeIt is reassigned, like acounter or a totalletvisible only in its blockOld code that needsfunction scopevarhoisted as undefined, leaksout of blocks

Key points

  1. 1let and const are block-scoped: a name declared inside braces does not exist after the closing brace.
  2. 2var is function-scoped. It ignores if and for blocks, and the same name can be declared again without an error.
  3. 3const fixes the binding, not the value: an object or array held in a const can still be changed.
  4. 4var declarations are hoisted with the value undefined. let, const and class are hoisted too, but reading them before their line throws a ReferenceError.
  5. 5Function declarations are hoisted with their body, so they can be called above the line that defines them.
What the exam guide checks here

Objective wording from the exam guide (English).

  • 1.1.K1var, let and const: function vs block scope, reassignment, redeclaration
  • 1.1.K2Hoisting and the temporal dead zone
  • 1.1.S1Choose the declaration and initial value that make given code behave as required

Lock it in

Answer scenario questions on this topic. Every option comes with an explanation.

Practise 1.1 · 12 questions