TivBroc TivBroc - 2 months ago 7
Javascript Question

Javascript type. Trying to understand how it works under the hood

I found some weird things about Javascript. For instance when I run in a node Shell (by just typing node) there are some statements that I do not understand.

> [] + []
'' (because [] is converted to an empty string ?)
> {} + []
0 (why 0 ?)
> x = ['10', '10', '10'] (this is ok)
['10', '10', '10']
> x.map(parseInt)
[ 10, NaN, 2 ] (really weird)


I would like to know how Javascript works under the hood to understand why I get those results (especially the last one)

Answer

This has been already answered many times, here's a quick outline of what's going on:

> [] + []
    = String([]) + String([])
    = [].join() + [].join()
    = '' + ''

> {} + []
    = {/*empty block */}; +[]
    = Number([])
    = Number(String([]))
    = Number('')
    = 0

> x = ['30', '20', '10']
> x.map(parseInt)
    = [
        parseInt('30', 0),
        parseInt('20', 1),
        parseInt('10', 2)
    ]
    = [10, NaN, 2]