1

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' ]
whiterook6
  • 3,270
  • 3
  • 34
  • 77
PURGEN
  • 47
  • 8

2 Answers2

3

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']
svltmccc
  • 1,356
  • 9
  • 25
2

Try like this, you will understand why !

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

in the first and second lines, you split '' (empty string).

Okkano
  • 230
  • 2
  • 9