Loops, and where your data lives

INPUT · Slides

Holding values together in an array

01 / 04

More values means more variables

If you want to hold three fruit names, you end up making three variables.

const fruit1 = "apple"; const fruit2 = "orange"; const fruit3 = "peach";

Three is still all right, but thirty gets away from you. And if someone asks you to show them all, that is thirty lines.

02 / 04

An array is one container

An array is what lets you hold several values as one lot. All you do is line the values up inside [ ], separated by ,.

One name, however many things inside. That is the idea of an array.

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

Result

["apple", "orange", "peach"]

03 / 04

The contents can be anything

It is not only strings that go in. Numbers are fine, so are true and false, and you can mix them.

In a real program, though, you will almost always be lining up things of the same kind — a list of scores, a list of names.

const scores = [80, 95, 60];console.log(scores);const flags = [true, false];console.log(flags);

Result

[80, 95, 60]
[true, false]

04 / 04

You can make an empty one too

Write [] and you get an empty array. You can set it up as "a box with nothing in it yet" and put things in later.

By the way, console.log on the array itself shows the whole thing wrapped in [ ] with , between. How to take out just one item is the next lesson.

const empty = [];console.log(empty);

Result

[]