CodeNest

Arrays and loops

Arrays store ordered lists of values:

const nums = [3, 8, 1];
nums.push(9);            // add to the end
console.log(nums.length); // 4
for (const n of nums) console.log(n);

Three array methods you will use constantly:

nums.map((n) => n * 2);          // new array, each item transformed
nums.filter((n) => n > 2);       // new array, only items that pass
nums.reduce((sum, n) => sum + n, 0);  // combine into one value

array.join(", ") turns an array into a string.

Try it

Print the doubled numbers on one line separated by , and then their sum:

6, 16, 2, 18, 8
Sum: 25
JavaScript in-browser
Next
Loading editor…

Press Ctrl/ + Enter or click Run to see the output here.