map in javsacaript code example
Example 1: map in javascript
// Use map to create a new array in memory. Don't use if you're not returning
const arr = [1,2,3,4]
// Get squares of each element
const sqrs = arr.map((num) => num ** 2)
console.log(sqrs)
// [ 1, 4, 9, 16 ]
//Original array untouched
console.log(arr)
// [ 1, 2, 3, 4 ]
Example 2: functions in map javascript
const map = new Map();
function foo() {
return "Hello World!";
}
map.set("foo", foo);
console.log(map.get("foo")()); // Output: "Hello World!