Array map()

map() accepts two arguments:

  • a function to run on each item and
  • an optional scope object

map() runs the given function on every item and returns the result of each function call in an array.

The function passed in receives three arguments:

  • the array item value,
  • the position of the item in the array
  • the array object itself.
 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
        var numbers = [1,2,3,4,5,4,3,2,1]; 
        
        var mapResult = numbers.map(function(item, index, array){ 
            return item * 2; 
        }); 
        document.writeln(mapResult); //[2,4,6,8,10,8,6,4,2] 
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

map() does not change the values contained in the array.

Home 
  JavaScript Book 
    Essential Types  

Array:
  1. The Array Type
  2. Array Built-in Methods
  3. Detecting Arrays
  4. Get and set array values
  5. Enumerating the Contents of an Array
  6. Array Length
  7. Array join() method
  8. Array concat()
  9. Array indexOf()
  10. Array lastIndexOf()
  11. Array every()
  12. Array filter() filters array with the given function.
  13. Array map()
  14. Array forEach()
  15. push() and pop():Array Stack Methods
  16. push(), shift():Array Queue Methods
  17. Array reduce()
  18. Array reduceRight()
  19. reverse():Reordering array
  20. Array slice()
  21. Array some()
  22. Array splice()
  23. Array sort()
  24. toString(), toLocaleString() and valueOf Array
  25. Array unshift()