user1096557
user1096557

Reputation:

Javascript array map method callback parameters

Javascript describes the map method syntax as:

arr.map(callback[, thisArg])

Parameters

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

I can write a JS function that capitalizes the first letter of each word in an array of strings as follows:

capyyIt(['john', 'nelson mandela', 'james booth'])     // returns ['John', 'Nelson mandela', 'James booth']

function capyyIt(names) {
  return names.map(function capIt(curr) { return curr[0].toUpperCase() + curr.slice(1).toLowerCase(); });
}
  1. How can I write capIt with 4 parameters (even though I may not be using them all)? I'm asking because I tried it with 4 parameters but it didn't seem to work.
  2. How can I write capIt as a non-immediately invoked function expression - something like:

    function capyyIt(names) {
        return names.map(capIt);
    }
    function capIt(curr,index,arr) {
        return curr[0].toUpperCase() + curr.slice(1).toLowerCase();
    }
    

Upvotes: 2

Views: 6928

Answers (1)

JoshSGman
JoshSGman

Reputation: 449

I'm not entirely clear on what you're asking but lets see if this is what you're looking for:

function capyyIt(names) {
  names.map(function(value, index, collection){
     capIt(val);
  })
}   

function capIt(name) {
  return name.toUpperCase() + curr.slice(1).toLowerCase();
}

The map function takes a callback argument that uses the value, index, and collection as arguments, you can't change this. Therefore if you want to do something to each value being mapped, you should do it inside the callback function.

Upvotes: 3

Related Questions