So far, each variable we've used holds just one piece of data. But what if you need to store multiple related items together, like all the names in a class or items on a shopping list?
Engagement Message
How might you group related values?
JavaScript provides a way to store an ordered collection of items: an array.
You create arrays using square brackets []
, with items separated by commas. For example: [1, 2, 3]
.
Engagement Message
What would happen if you forgot to include commas between array items like [1 2 3]
?
Arrays are very flexible. They can hold items of different data types, including numbers, strings, and even booleans, all in the same array!
Example:
let myStuff = [10, "hello", 4.5, true];
Engagement Message
Can an array contain both the number 50
and the string "score"
?
Just like other data types, you assign an array to a variable using let
and =
.
