user1554264
user1554264

Reputation: 1224

Increasing understanding map function() and syntax

Consider the following code:

var watchList = [
   {
      "Metascore": "70",
      "imdbRating": "8.3",
      "imdbVotes": "972,584",
      "imdbID": "tt0372784",
      "Type": "movie",
      "Response": "True"
   },
   {

      "Metascore": "83",
      "imdbRating": "7.9",
      "imdbVotes": "876,575",
      "imdbID": "tt0499549",
      "Type": "movie",
      "Response": "True"
   }
  ];

console.log(watchList.length);

const rating = watchList.map((function test (item) { 
  console.log(item);
  return {
    title: item["Title"],
    rating: item["imdbRating"]
  };
}));

console.log(JSON.stringify(rating));

MDN link

Just have a few questions in relation to map() syntax in my specific code block.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

Use of map:

`const rating = watchList.map((function test (item) {}` 

Referencing against the MDN JavaScript docs am I correct in saying that in this case:

1) That test is the argument supplied to the callback parameter of the map() method? It does not state callback is an optional parameter, so I'm confused going against the MDN syntax above that there are no errors in the console when an anonymous function is passed that has no name.

2) That item is the argument supplied to the currentValue parameter of the map() method which is each element in the watchList array?

Upvotes: 0

Views: 57

Answers (2)

Angelotti
Angelotti

Reputation: 750

As you see in MDN:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

it's as write

var new_array = arr.map(function(item){.....})

the value in[] are optional and the last is to bindig the "this"

especially if you will use arrow function

var new_array = arr.map(item=>{})

you can also create a function

function test(item){.....}

and use in callback

var new_array = arr.map(test(item))

Upvotes: 0

Sathiraumesh
Sathiraumesh

Reputation: 6117

The MDN docs specify what type of function that should be passed like the signature. For description, they have used a name function called the callback. any function named or anonymous will do the work.

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

here the index and the array are optional

enter image description here

so for the first question it's a yes

And for the second point you mentioned, the item maps to the current value so it is a yes too. For further learn about passing functions to methods or functional programming concepts with javascript.

Upvotes: 1

Related Questions