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

AttributeDescription
Syntaxarray.map((currentValue, index, array) => {/* return element */})
Return ValueA new array with each element being the result of the callback function.
Original ArrayUnchanged — map() does not mutate the original array.

🔸 Simple Number Transformation

AttributeValueDescription
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

AttributeValueDescription
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

AttributeValueDescription
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

AttributeValueDescription
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

AttributeValueDescription
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