Changing Items

Grade 7, page 4 of 14. A one-minute read.

You can replace an item by assigning a new value to its index:

JavaScript
const foods = ["burger", "omelet", "pancakes", "soup"];
foods[1] = "pasta";
console.log(foods);

It prints

[ 'burger', 'pasta', 'pancakes', 'soup' ]

Wait a minute! We created foods with const. Isn't that supposed to be locked?

Here's the key thing to understand: const locks the variable, not the contents. It means foods will always point to this same train. You can't swap it for a completely different train. But you can still change who's sitting in the carriages.

JavaScript
const foods = ["burger", "omelet"];

foods[0] = "bean stew";           // ✅ allowed: changing the contents
console.log(foods);

foods = ["pizza", "burgers"];   // ❌ not allowed: replacing the whole array

It prints

[ 'bean stew', 'omelet' ]
Uncaught TypeError: Assignment to constant variable.

So for arrays, it's still best to use const almost all the time, even if you'll be adding, removing and changing items. You'll only need let if you plan to replace the entire array with a brand-new one.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning