Ufuk's Blog

map array helper method

☕️ 1 min read

This is the second stop on array helper methods in JavaScript. Let’s say we have an array of numbers and we need to take that values from the array multiply them, take the new values and push to a new array. That sounds like a lot of job right? Let’s take a look at the classic way of doing this first.

const nums = [1, 2, 3, 4, 5];
const doubledNums = [];

for (let i = 0; i < nums.length; i++) {
  doubledNums.push(nums[i] * 2);
}

With map array helper method, we can do the same job with less code like below.

const nums = [1, 2, 3, 4, 5];

const doubledNums = nums.map(num => num * 2);

Just wow! This is all I can say.