1

I'm relatively new to JavaScript and I want to understand the logic behind this snippet of code I found on this site: [...num+''].map(n=>+n) //[1, 2, 3, 4, 5]
I would've asked in a comment on the original answer, but I don't have enough rep... yet.

I was working on a coding challenge on Codewars and this answer from another question on this site worked really well, and was really concise, but I'm relatively new to JavaScript, and would like some clarification on why this worked.

The original post basically said that this function returns a digits in a number as an array of strings:

let num = 12345;

[...num+''] //["1", "2", "3", "4", "5"]

and that this little addition converted the strings back to integers:

[...num+''].map(n=>+n) //[1, 2, 3, 4, 5]

I would just google this on my own, but I don't know what any of these syntaxes are actually called...

Skouzini
  • 143
  • 1
  • 10
  • 3
    `num + ''` converts a number into a string; `...` is spread syntax used to turn iterable values into comma separated elements. `n => +n` is an arrow function, the longer version is `n => { return +n; }`. `+n` is a shortcut to turn a string into a number. –  Oct 21 '19 at 18:12
  • @ChrisG so `num+''` would work for any number and `+n` would work for any string made of digits? – Skouzini Oct 21 '19 at 18:17
  • 1
    Basically yes; `+"a"` will evaluate to `NaN`. –  Oct 21 '19 at 18:18
  • 1
    @Skouzini `anyVar+''` will work for any datatype and will implicitly convert to string. `+anyVar` will convert any type to a number. – VLAZ Oct 21 '19 at 18:19
  • @ChrisG @VLAZ okay, that makes sense. Thank you! So would that mini function need to be assigned to a variable, or would it alter the variable `num`? – Skouzini Oct 21 '19 at 18:27
  • 1
    You need to assign it to something. The only operators that modify variables are auto-increment and assignments. – Barmar Oct 21 '19 at 19:01

0 Answers0