JavaScript Arrays for Beginners: Keep Your Items in One Place
A list of names, scores, or favourite foods can all fit in one JavaScript array. Let’s create one and learn how to use it, with results you can see on the page.
What is an array?
An array is a variable that holds an ordered list of items. Instead of making a separate variable for every fruit, you can keep them together in one array.
const fruits = ["apple", "banana", "orange"];The square brackets [ ] make the array. Each fruit is a separate item, and commas divide the items.
See your result on the page
You do not need to open the browser Console for this lesson. Open the Playcode123 Code Sandbox, replace its starter code with the complete page below, then choose Run Code. The result appears in the preview below the editor.
<!doctype html>
<html>
<body>
<h1>My fruit list</h1>
<p id="result">Your result will appear here.</p>
<script>
const fruits = ["apple", "banana", "orange"];
document.getElementById("result").textContent = fruits[0];
</script>
</body>
</html>What you should see: the page shows apple. The last line puts the first fruit on the page so you can see the result. You can leave that line as it is while you follow the next examples.
Get an item from an array
Every item has a position called an index. JavaScript starts counting at 0, so the first item is at index 0, the second is at index 1, and so on.
In the Sandbox, change fruits[0] on the last line to fruits[1], then choose Run Code again. The preview will show banana.
Remember: the first item is
fruits[0], notfruits[1].
Change an item
You can use an index to replace an item. Add this line just above the line that starts with document.getElementById:
fruits[1] = "pear";Now change the last line back to fruits[1] and choose Run Code. The preview shows pear.
Add an item to the end
Use push() to add a new item at the end. Add this line above the line that starts with document.getElementById:
fruits.push("grape");Then change the last line to fruits[3] and run the code. The preview shows grape. Its index is 3 because it is the fourth item.
Count the items
The length property tells you how many items are in an array. Change the last line to:
document.getElementById("result").textContent = fruits.length;Choose Run Code. The preview shows 4, because the array now has four fruits.
Try it yourself
Change the array to a list of your favourite pets. Then change the last line to show the first pet. Try adding another pet with push() and show the number of pets with length.
Quick recap
- An array stores an ordered list of items.
- Use an index such as
fruits[0]to choose an item. Indexes start at zero. - Use
push()to add an item at the end. - Use
lengthto count the items. - Choose Run Code to see each result in the Sandbox preview.
Arrays are useful whenever you have several related items. Try changing the fruit names in the example and see what happens.
