Loops, and where your data lives

INPUT · Slides

Changing what is in an array

01 / 06

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 / 06

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 / 06

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 / 06

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]

05 / 06

Assigning past the end grows the array

Reading past the end gave undefined, but assignment is different. Assign to a number the array does not have yet, and the array grows to reach that length.

The positions you skipped get filled with undefined. Do this by accident and the array ends up longer than you meant, which can be confusing.

const nums = [1, 2, 3];nums[5] = 99;console.log(nums);console.log(nums.length);

Result

[1, 2, 3, undefined, undefined, 99]
6

06 / 06

Assign it to another variable and the contents are shared

Assign an array to another variable and you get two names pointing at the same array — the contents are not copied. Change one and the other looks changed too.

This is a property arrays share with objects, and it is surprising the first time you see it.

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

Result

["z", "b"]