Arrays
You'll learn to read and change arrays, lists of values in order, using positions that start at 0.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You want to keep many values together, in order: the batting order of a cricket team, or the marks of every student in a class. A list of values in order is called an array. You write it in square brackets:
const players = ["Tamim", "Shakib", "Mushfiq"];console.log(players[0]); // "Tamim"console.log(players.length); // 3
Each item has a position number, called its index. The index starts at 0, not 1. So the first
player is players[0] and the third is players[2]. length tells you how many items there are.
Because counting starts at 0, the last item is always at length - 1. People often write
players[players.length], which is one step past the end. That gives undefined, not an error, so the
bug can hide for a while.
A few tools you'll use all the time:
players.push("Liton")adds an item to the end.players.includes("Shakib")answerstrueorfalse: is it in the list?players.indexOf("Shakib")gives its index, here1, or-1if it is not there.
An array can hold any values: numbers, strings, booleans, even objects or other arrays. In a real app you will mostly see arrays of objects, like a list of users.
When you read code with [ ] after a name, ask: which position is this, counting from 0?
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1const players = ["Tamim", "Shakib", "Mushfiq"];2players.push("Liton");3console.log(players.length, players[1]);
lastItem should give back the last item of any list. Fix it so all three checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3With
const days = ["Sat", "Sun", "Mon"];, what isdays[1]? - 2 / 3With the same
days, what isdays[days.length]? - 3 / 3What is
["Rafi", "Nusrat"].indexOf("Sadia")?