js map sample code example
Example 1: javascript map function
/* Answer to: "javascript map function" */
/*
<Array>.map() - One of the most useful in-built methods in JavaScript (imo).
The map() method creates a new array populated with the results of calling
a provided function on every element in the calling array.
For more information, click on the source link.
Let me make some examples of it's uses:
*/
let array = [1, 4, 9, 16];
array.map(num => num * 2); // [2, 8, 18, 32];
array.map(pounds => `£${pounds}.00`); // ["£1.00", "£4.00", "£9.00", "£16.00"];
array.map(item => Math.sqrt(item)); // [1, 2, 3, 4];
Example 2: map in javascript
let myMap = new Map()
let keyString = 'a string'
let keyObj = {}
// setting the values
myMap.set(keyString, "value associated with 'a string'")
myMap.set(keyObj, 'value associated with keyObj')
myMap.set(keyFunc, 'value associated with keyFunc')
myMap.size // 3
// getting the values
myMap.get(keyString) // "value associated with 'a string'"
myMap.get(keyObj) // "value associated with keyObj"
myMap.get(keyFunc) // "value associated with keyFunc"