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++;
}
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.
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;
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.
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]
Notes:
map() does not modify the original array.
The returned array will have the same length as the original.
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]
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.