When diving into JavaScript, you'll quickly come across different tools that help make your code more efficient and readable. In this post, we’ll explore three essential concepts:
-
while
loop -
map()
function - arrow functions (
=>
)
Let’s break them down with simple examples.
🔁 1. The while
Loop
A while
loop runs as long as a certain condition is true. It’s useful when you don’t know exactly how many times the loop should run.
🔹 Syntax:
while (condition) {
// code to run
}
✅ Example:
let i = 0;
while (i < 5) {
console.log("Number:", i);
i++;
}
🧠 What’s happening?
- The loop checks if
i < 5
- If true, it runs the code inside
-
i++
increasesi
by 1 each time - When
i
hits 5, the loop stops
🔄 2. The map()
Function
The map()
function is used to transform each item in an array and return a new array with the results.
🔹 Syntax:
let newArray = oldArray.map(callbackFunction);
✅ Example:
let numbers = [1, 2, 3];
let doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // [2, 4, 6]
➡️ 3. Arrow Functions
Arrow functions are a shorter way to write functions. They’re especially useful with methods like map()
.
🔹 Syntax:
const functionName = (parameters) => {
// function body
};
✅ Example:
Here’s the same map()
example with an arrow function:
let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
📝 If there’s only one parameter and one expression, you can skip the parentheses and curly braces.
🔄 Combining All Three!
Let’s say you want to double the numbers in an array using a while
loop and arrow functions.
let numbers = [1, 2, 3, 4];
let doubled = [];
let i = 0;
while (i < numbers.length) {
doubled.push((num => num * 2)(numbers[i]));
i++;
}
console.log(doubled); // [2, 4, 6, 8]
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.