0

When I execute

console.log( (4 + [] + 8) )

I get the result of 48 and when I execute [] alone it gives 0. How does it work?

j08691
  • 204,283
  • 31
  • 260
  • 272

2 Answers2

3

Because this is a sum of a number and an array, javascript is converting both to strings.

Therefore:

'4' + '' + '8' = '48' (notice that the result is a string, not a number)

If you add more elements to the array, it will work like this

4 + [1, 2] + 8 = '41,28'

This happens because arrays, by default, become strings by concatenating values with ,.

Another example

4 + [1, 2, 3, 4, 5] + 8 = 41,2,3,4,58

Note: If you try summing two arrays they will also become strings, as javascript doesn't have a native implementation for summing arrays.

[1, 2] + [3, 4] = '1,23,4'

Pedro Moreira
  • 965
  • 5
  • 8
0

Like explained in the comments. When you use the + operator on an array to a variable of a different type, the js engine will call it as a string via [].toString(). Adding a number to a string also converts the numbers to a string.

DarkMukke
  • 2,469
  • 1
  • 23
  • 31