Today, I dived into some essential JavaScript concepts that are widely used in real-world web development:
1.array.map()
2.Arrow Functions (=>
)
3.Callback Functions
Let me walk you through what I learned
What is array.map()
?
The map()
method is used to transform each element of an array and return a new array.
It doesnβt change the original array.
Example:
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // [2, 4, 6, 8]
Arrow Functions (ES6 Feature)
Arrow functions are a shorter way to write functions.
Syntax:
// Traditional function
function greet(name) {
return `Hello, ${name}`;
}
// Arrow function
const greet = (name) => `Hello, ${name}`;
Arrow functions are often used in methods like .map()
, .filter()
, and .forEach()
.
Callback Functions
A callback function is a function passed as an argument to another function.
π‘ map()
is a good example β it takes a callback function that runs on every element.
Example with .map()
and arrow function:
const numbers = [5, 10, 15];
const squared = numbers.map((num) => num * num);
console.log(squared); // [25, 100, 225]
Here, (num) => num * num
is a callback passed into map()
.
Why These Are Useful?
-
map()
helps transform data (useful in frontend apps). - Arrow functions make your code clean and short.
- Callbacks allow flexibility in function behavior.
Top comments (0)