A few more methods you will meet daily.
forEach
forEach calls a function for each item. It returns nothing, so use it for side effects such as printing or updating the page.
["a", "b", "c"].forEach((letter, index) => {
console.log(index, letter);
});
Two limits: you cannot stop it with break, and it does not wait for async callbacks. For those cases use for...of.
join
join() turns an array into a string, with a separator you choose (a comma by default).
const words = ["Learn", "modern", "JavaScript"];
console.log(words.join(" ")); // → Learn modern JavaScript
console.log(words.join("-")); // → Learn-modern-JavaScript
console.log(words.join("")); // → LearnmodernJavaScript
console.log([1, 2, 3].join()); // → 1,2,3
concat
Joins arrays into a new one. Spread is usually clearer, but you will see concat in older code.
console.log([1, 2].concat([3, 4], 5)); // → [1, 2, 3, 4, 5]
fill
Replaces items with one value. Often used to make a starting array.
console.log(new Array(4).fill("-")); // → ["-", "-", "-", "-"]
console.log([1, 2, 3, 4].fill(0, 2)); // → [1, 2, 0, 0]
Careful: filling with an object puts the same object in every slot. Use Array.from({ length: n }, () => ({})) instead.
at
Reads an item, accepts negative numbers.
console.log([10, 20, 30].at(-1)); // → 30
console.log([10, 20, 30].at(0)); // → 10
Array.of and entries/keys/values
console.log(Array.of(7)); // → [7]
console.log([...["a", "b"].entries()]); // → [[0, "a"], [1, "b"]]
console.log([..."ab"].keys().next().value); // → 0
Which array method should I use?
| Goal | Method |
|---|---|
| Do something for each item | forEach or for...of |
| Transform each item | map |
| Keep some items | filter |
| One result from many | reduce |
| Find one item | find |
| Yes or no questions | some, every, includes |
| Join into text | join |
Practice them together in the Product Filter project.