Beginner 8 min

Variables with let and const

Choose between reassignment and a fixed binding in JavaScript.

Choose the declaration

Use const when the name should keep referring to the same value. Use let when the code needs to reassign that name. Both declarations are scoped to their enclosing block.

How it works

A binding connects a name to a value. Reassignment changes that connection. An object’s contents can still change through the same binding, so a const array can receive an additional value. Use a separate array if you need to preserve the original contents.

Perform the update

remaining = remaining - picked reads both values, subtracts them, and binds the result to remaining. Use console.log to observe what happened. Logging before and after the assignment makes the difference visible.

Tell bindings and objects apart

A const array can still change contents with operations like push. The binding remains fixed to that array. A new assignment such as cart = [] is a separate operation and fails when cart was declared with const.

Code example

let remaining = 7;
const picked = 2;
remaining = remaining - picked;
console.log(remaining);

Check your understanding

Each pack holds four cards. Print the number of cards after packing the input number of packs.

See the example and explanation
Example 1
Given 3
Answer 12
Example 2
Given 0
Answer 0

Multiply packs * cardsPerPack and print the result. This works for zero packs because zero times four is zero.

Open practice problem
Next lessonTypes, conversions, and equality