Search code examples
javascriptmethodssplittype-conversion

Ways to split a Number into an Array


Let's say we have a number:

let num = 969

I'm trying to split this number into an array of digits. The first two methods do not work, but the third does. What is the difference?

num + ''.split('')             // '969'
num.toString() + ''.split('')  // '969'
String(num).split('')          // [ '9', '6', '9' ]

Solution

  • Well, let's look how it works

    num + ''.split('') works like

    1. num is a number
    2. ''.split('') is empty array and it's not a number
    3. so, we have sum of a number and not a number, we will cast num and [] to string
    4. num to string is '969', [] to string is '' (empty)
    5. '969' + '' = '969'

    num.toString() + ''.split('') works like

    1. num.toString() is a string
    2. ''.split('') is empty array
    3. so, we have sum of a string and not a string, we will cast [] to string
    4. [] to string is '' (empty)
    5. '969' + '' = '969'

    String(num).split('') works like

    1. lets cast num to string
    2. and split it by ''
    3. result of split is array ['9', '6', '9']