Suomi Suomi - 1 month ago 5
Javascript Question

Why do I need the index parameter in a function, when going through objects in an array?

In the getFullName function, why do I need the index parameter?

This example code is from W3 School http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_map3

EDIT: Apparently I don't need it. In what type of case would I need it? Or is that even relevant to ask in this context?



var persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];


function getFullName(item,index) {
var fullname = [item.firstname,item.lastname].join(" ");
return fullname;
}

function myFunction() {
document.getElementById("demo").innerHTML = persons.map(getFullName);
}

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get a new array with the full name of each person in the array.</p>
<button onclick="myFunction()">Try it</button>

<p>New array: <span id="demo"></span></p>

</body>
</html>





Why do I need the index parameter in a function, when going through objects in an array?

Answer

Its just design of the map function, May be you don't need the index at this scenario but there might be scenario like, If its 3rd element update the data else do nothing!!. At such scenarios you make use of the index.

You can just neglect it from the function definition if don't require it.

function getFullName(item){
//..
}