3.js-arrays.md
Quiz
~/ hackweb.dev
...
~/
/tutorials
/en/js/js-arrays/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
en/tutorials/js/3js-arrays
# JavaScript Arrays Arrays hold ordered lists of values. Everything in JavaScript has an array method waiting for it. ## Creating and accessing Use square brackets to create an array. Indexes start at 0. ```js const fruits = ["apple", "banana", "cherry"]; console.log(fruits[0]); console.log(fruits.length); ``` ## Adding and removing `push` adds to the end, `pop` removes the last item. ```js const stack = []; stack.push("a"); stack.push("b"); console.log(stack); stack.pop(); console.log(stack); ``` ## Looping `for...of` walks each item in order. ```js const names = ["Ada", "Grace", "Linus"]; for (const name of names) { console.log("hi " + name); } ``` ## Transforming with map and filter `map` builds a new array, `filter` keeps only matching items. ```js const nums = [1, 2, 3, 4, 5]; const doubled = nums.map((n) => n * 2); const evens = nums.filter((n) => n % 2 === 0); console.log(doubled); console.log(evens); ```
Submit suggestion
cancel