DEV Community

P Mukila
P Mukila

Posted on

Today I learned-JavaScript: while Loops, Arrow Functions, and the map() Method

1.Looping with while

The while loop continues executing a block of code as long as a condition is true.

Syntax:

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}
Enter fullscreen mode Exit fullscreen mode

Notes:

Be careful to increment the counter (i++), or you might create an infinite loop.

Use while when you don't know ahead of time how many times you'll loop.
Enter fullscreen mode Exit fullscreen mode

2.Arrow Functions

Arrow functions are a shorter syntax for writing functions. They're especially useful for small functions or callbacks.
Syntax:

// Regular function
function add(a, b) {
  return a + b;
}

// Arrow function
const add = (a, b) => a + b;

Enter fullscreen mode Exit fullscreen mode

Key Features:

Short and clean syntax.

Does not have its own this (inherits from parent scope).

Great for array methods like map, filter, forEach, etc.
Enter fullscreen mode Exit fullscreen mode

3.map() Method

The map() method creates a new array by applying a function to each element in an existing array.
Syntax:

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]

Enter fullscreen mode Exit fullscreen mode

Notes:

map() does not modify the original array.

The returned array will have the same length as the original.
Enter fullscreen mode Exit fullscreen mode

Example: Combining All Three

let nums = [1, 2, 3, 4, 5];
let i = 0;

while (i < nums.length) {
  nums[i] += 1;
  i++;
}

const doubled = nums.map(n => n * 2);
console.log(doubled); // [4, 6, 8, 10, 12]

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.