Excellent — this is a JavaScript arrow function + map() example! ๐
Let’s go through it step by step:
๐ง Code:
๐ 1️⃣ map() method:
-
The
.map()method creates a new array by applying a function to each element of the original array. -
It does not modify the original array.
Example:
➡️ It will take each element:
-
"Ram"→"RAM" -
"shyam"→"SHYAM"
and return a new array["RAM", "SHYAM"].
๐งฉ 2️⃣ let r = a.map(x => x.toUpperCase())
✅ Short arrow function
If there’s only one expression, you can omit {} and return.
It automatically returns the result.
So:
means “take x and return x.toUpperCase()”.
๐ข Output: ["RAM", "SHYAM"]
๐งฉ 3️⃣ let t = a.map(x => { return x.toUpperCase() })
✅ Long form with braces {}
When you use {}, you must explicitly write return.
Otherwise, it won’t return anything.
๐ข Output is same: ["RAM", "SHYAM"]
๐งฉ 4️⃣ let y = a.map(x => ( x.toUpperCase() ))
✅ Parentheses form ( )
When you wrap the expression inside parentheses, it’s like saying:
"Return this expression's value"
So this is also equivalent to the first one.
๐ข Output: ["RAM", "SHYAM"]
๐ฆ Final Output:
⚙️ Summary Table:
| Code Form | Requires return? | Output |
|---|---|---|
x => x.toUpperCase() | ❌ No | ["RAM", "SHYAM"] |
x => { return x.toUpperCase() } | ✅ Yes | ["RAM", "SHYAM"] |
x => ( x.toUpperCase() ) | ❌ No | ["RAM", "SHYAM"] |
Comments
Post a Comment