0

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)

  • 3
    The last example you have is mentioned in the mdn documentation for `map()` at the 'Tricky use Case' section: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map . In summary, the problem comes from optional function parameters. – httpNick Sep 19 '16 at 21:35
  • The ECMAScript spec is the place to look if you want to know how things are designed to work. Right now, this is an accumulation of commonly asked questions. –  Sep 19 '16 at 21:41

1 Answers1

4

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]
georg
  • 211,518
  • 52
  • 313
  • 390