8

Explain this Javascript expression just like I'm five

 3 years ago
source link: https://dev.to/theodesp/explain-this-javascript-expression-just-like-im-five-d35
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Explain this Javascript expression just like I'm five

Nov 22, 2017

・1 min read

Explain to me the result of this expression in Javascript:

["10", "10", "10", "10"].map(parseInt)
Enter fullscreen modeExit fullscreen mode

Discussion (6)

pic

CollapseExpand

parseInt() takes to arguments, a string and a radix. I usually pass just the string I want converting as a number, you are passing both the string and the radix!

map gives us the value and the index (and the actual array)

["10", "10", "10", "10"].map( (value,index) => ... )

By just doing .map(parseInt) parseInt is taking both the value and the index.

Basically the second iteration is parseInt('10',1) and returns NaN.

Finally, to test that that's what happens, the following would return "0: 10" "1: 10" "2: 10" "3: 10"

function myFunc(value, i){
  console.log(`${i}: ${value}`)
}
["10", "10", "10", "10"].map(myFunc)

Comment button Reply

CollapseExpand

["10", "10", "10", "10"].map(parseInt)  ==>  [10, NaN, 2, 3]
Enter fullscreen modeExit fullscreen mode

This is because from Array.prototype.map

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.
callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

Also from parseInt()

Syntax: parseInt(string, radix);

So when this is executing it will return

[
    parseInt("10", 0),
    parseInt("10", 1),
    parseInt("10", 2),
    parseInt("10", 3)
]
Enter fullscreen modeExit fullscreen mode

Comment button Reply

CollapseExpand

take a list of strings that represent numbers and return a new list with all the strings converted to the numbers they represent, but they now have the data type of number

Comment button Reply

CollapseExpand

if you execute this statement, the result will be [10, NaN, 2, 3]. Why?
But if you use parseFloat instead of parseInt, you will get the list of numbers.
I can't really explain why this is happening. But you can use this one as a replacement:

["10", "10", "10", "10"].map(function(x){ return parseInt(x); })

Comment button Reply

CollapseExpand

whoa, you're right. Can someone explain what is happening?

I usually write map functions like this

["10", "10", "10", "10"].map(item => parseInt(item));

and that does indeed return [10, 10, 10, 10].

passing just parseInt as a callback.. how does it know what arguments to take?

Thread

Thread


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK