I am trying to write a function that returns the doubled values of an array using the map method. I have never used this before and have read up on how to use it, but obviously I am doing something wrong as it’s not working and I am sure it should be a simple solution.
Is it something to do with the parameters? I think I still get confused when a parameter is presented as, say (x), but actually contains an array of values…(this is how the problem was presented, as function(x))…
Thanks for any help anyone can offer…
function maps(x) {
let doubled = x.map((x) => x * 2);
return doubled;
}
It accepts single argument (which should be an array, as that’s how it’s used later).
maps(1, 2) passes two arguments, of which first is integer, so that will result in error. maps([1, 2]) passes single argument, which is an array. This is the one that should work. From my tests it does.
Regarding your doubts about parameters. Generally it’s better to use more unique names than x, however in:
function maps(x) {
let doubled = x.map((x) => x * 2);
return doubled;
}
The x from function maps(x), x.map(..., and (x) => x * 2 are two different x.
(x) => x * 2 is separate function, which has it own scope. As it takes x as parameter, the x used inside of the function will be the x that’s passed to the function. Not the x from the outer scope.
Great (and very clear) answer, thank you so much. It makes so much sense the way you have put it.
Also about the x’s being different is great to know as tbh, I don’t think I understood that properly even though it makes perfect sense now that you have pointed it out and when re-reading the code. I should really use a different variable in the second part then to avoid confusion…
Thank you so much for your response, very much appreciated.