Map on an array is simple enough -
|
|
map
will specify one element at a time, which is passed to the callback function as val
.
Let’s say, we ignore the val
.
|
|
The above code works too. map
takes a callback function and runs it on every element, so no problem with the above code.
Now, consider the below.
|
|
Oops. Let’s see what map
passes to the callback function.
|
|
This is not a problem, so let’s expand our horizon.
|
|
We can see what’s happening - there are multiple arguments passed everywhere, and there may be an issue with the callback and the way map has passed the arguments.
Let’s compare notes with the definition of a map
. Map accepts a callback function, values (one at a time), and passes across the values to the callback function.
parseInt
accepts an input to parse, and radix (defaulted to 10). Radix represents the base of the number in mathematics.
Therefore, in our case parseInt
is being passed both the actual value and index.
- 1, 0
- 3, 1
- 5, 2
parseInt sees this and decides that the value passed is not a real number since 3 and 5 do not exist in the radix 1 and 2 respectively. The evaluation will result in -
|
|
Avoiding these errors
Avoid the above errors and the resulting frustration by always using an anon function.
|
|
The code is explicit in specifying the arguments and is highly readable.