JavaScriptLesson 7 of 10Jump to practice
Arrays
Work with lists of values: add and remove items, search them, and transform them with map and filter.
An array is an ordered list of values. You met arrays in the variables lesson. Now let’s do things with them.
const fruits = ["apple", "banana", "pineapple"];
// index: 0 1 2
Adding and removing
| Method | What it does |
|---|---|
push(x) |
Add x to the end |
pop() |
Remove the last item (and give it back) |
unshift(x) |
Add x to the start |
shift() |
Remove the first item |
<script>
const queue = ["Emma", "Diego"];
queue.push("Sofia");
console.log("After push:", queue);
const served = queue.shift();
console.log("Served:", served);
console.log("Still waiting:", queue);
console.log("How many:", queue.length);
</script>Result
Searching
includes(x)givestrueorfalse.indexOf(x)gives the position, or-1if it isn’t there.find(fn)gives the first item that passes a test.
Transforming: map, filter and forEach
These three take a function and run it on every item. They replace most loops.
| Method | Gives you |
|---|---|
forEach(fn) |
Nothing. Just runs fn on each item |
map(fn) |
A new array, with each item changed by fn |
filter(fn) |
A new array, with only the items where fn returns true |
<script>
const prices = [40, 250, 90, 120, 60];
const halfOff = prices.map((p) => p / 2);
console.log("Half off:", halfOff);
const cheap = prices.filter((p) => p < 100);
console.log("Under 100:", cheap);
const total = prices.reduce((sum, p) => sum + p, 0);
console.log("Total:", total);
prices.forEach((p, i) => console.log("Item " + i + " costs " + p));
</script>Result
map and filter never change the original array. They hand you a new one.
Joining into text
join() turns an array into one string:
["HTML", "CSS", "JavaScript"].join(", "); // "HTML, CSS, JavaScript"
Practice
Check what you just learned. Fill in the missing code, then answer the quiz.
Exercise 1Solved
Add
"grape"to the end of the array.const fruits = ["apple", "banana"]; fruits.("grape");Exercise 2Solved
Check whether the list contains
"apple"(givestrueorfalse).console.log(fruits.("apple"));Exercise 3Solved
Keep only the prices under 100.
const prices = [40, 250, 90, 120]; const cheap = prices.((p) => p < 100);
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.
