Loops, and where your data lives

INPUT · Slides

Changing what is in an array

01 / 04

If you can take it out, you can put it back

fruits[1] got you the second item. Put that same writing on the left of an = and you can put a new value there.

The shape is array[number] = new value;. Exactly the same thinking as updating a variable.

const fruits = ["apple", "orange", "peach"];fruits[1] = "grape";console.log(fruits);

Result

["apple", "grape", "peach"]

02 / 04

The old value goes

When you write over it, the old value does not stay. What is at that position is simply replaced.

The positions you did not touch stay as they were. Only the number you named changes.

const nums = [10, 20, 30];nums[0] = 99;console.log(nums[0]);console.log(nums[1]);

Result

99
20

03 / 04

const still lets you change the contents

This one may surprise you. Even an array made with const, you can change the contents of.

What const forbids is "putting something else under that name", not "reaching into the container". So arrays are normally made with const.

const list = ["a", "b"];list[0] = "z";console.log(list);

Result

["z", "b"]

04 / 04

Updating using itself

Just as with variables, you can put the current value on the right. Shorthand like += works here as well.

That gets you things like adding to a score or taking down some stock.

const scores = [80, 60];scores[0] = scores[0] + 10;scores[1] += 5;console.log(scores);

Result

[90, 65]