codegurukool.com · Free coding tutorials & online compiler

Home › JavaScript Tutorial › Arrays and loops

Arrays and loops

Work with lists of values.

Arrays hold ordered values. Methods like map and filter build new arrays without manual loops.

Commands in this lesson

map

Definition: Builds a new array by transforming each item.

Syntax:

array.map(function);

Example:

console.log([1, 2, 3].map(function(x){ return x * 2; }));

filter

Definition: Builds a new array with only the items that pass a test.

Syntax:

array.filter(function);

Example:

console.log([1, 2, 3, 4].filter(function(x){ return x % 2 === 0; }));

Example code

<ul id="u"></ul>
<script>
  const nums = [1, 2, 3, 4, 5];
  const even = nums.filter(n => n % 2 === 0).map(n => n * 10);
  for (const v of even) {
    const li = document.createElement("li");
    li.textContent = v;
    u.appendChild(li);
  }
</script>

Run this code in the online editor

← EventsConditionals →