Nearby lessons
36 of 40🔹 Array map() Method in JavaScript
📌 What is Array map() Method?
map() is a non-mutating method that creates a new array by calling a provided function on every element in the original array.
It does not change the original array but returns a new one based on the transformation.
Very useful for transforming data like multiplying, formatting, or extracting values from objects.
🔸 Basic Syntax
| Attribute | Description |
|---|---|
Syntax | array.map((currentValue, index, array) => {/* return element */}) |
Return Value | A new array with each element being the result of the callback function. |
Original Array | Unchanged — map() does not mutate the original array. |
🔸 Simple Number Transformation
| Attribute | Value | Description |
|---|---|---|
Example |
<pre><code>
const nums = [1, 2, 3, 4];
const doubled = nums.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]
</code></pre> |
🔸 Convert Strings to Uppercase
| Attribute | Value | Description |
|---|---|---|
Example |
<pre><code>
const fruits = ["apple", "banana", "cherry"];
const upperFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(upperFruits); // ["APPLE", "BANANA", "CHERRY"]
</code></pre> |
🔸 Extracting Specific Fields from Array of Objects
| Attribute | Value | Description |
|---|---|---|
Example |
<pre><code>
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 28 }
];
const names = users.map(user => user.name);
console.log(names); // ["Alice", "Bob", "Charlie"]
</code></pre> |
🔸 Add Index to Each Item
| Attribute | Value | Description |
|---|---|---|
Example |
<pre><code>
const langs = ["HTML", "CSS", "JavaScript"];
const withIndex = langs.map((lang, index) => index + ": " + lang);
console.log(withIndex); // ["0: HTML", "1: CSS", "2: JavaScript"]
</code></pre> |
🔸 Mapping with Conditional Logic
| Attribute | Value | Description |
|---|---|---|
Example |
<pre><code>
const numbers = [1, 2, 3, 4, 5];
const evenOrOdd = numbers.map(n => (n % 2 === 0 ? "Even" : "Odd"));
console.log(evenOrOdd); // ["Odd", "Even", "Odd", "Even", "Odd"]
</code></pre> |
Keep Going!JS - String Methods