0

i have

a = [[1,2,3],[4,5,6]]

How come when i write

console.log(...a.shift()) it gives me 1 2 3 but not 1,2,3 nor [1, 2, 3] can anyone explain me the mechanism behind this?

  • 3
    You're calling `console.log(...[1,2,3])` which is the same as calling `console.log(1,2,3)` – Paul Sep 26 '19 at 21:58
  • right but why does it turn an array into numbers? just confusing for me to have a method that is similar to ```console.log([1,2,3].join(" ")) ``` i know it would turn it into string if i use ```.join``` so thats why im just curious about the mechanism underneath the spread operator – Duong Nguyen Sep 26 '19 at 22:05
  • Please explain why you were expecting `1,2,3` or `[1, 2, 3]`. – Bergi Sep 26 '19 at 22:06
  • The spread syntax just causes `console.log` to receive multiple arguments, one for each element of the array (doesn't matter whether they're numbers or not). It's `console.log`'s choice to display them with whitespace in between, it could do anything else. – Bergi Sep 26 '19 at 22:08

2 Answers2

2

a.shift() returns the first element of the array, which is [1, 2, 3]. So your code is equivalent to:

console.log(...[1, 2, 3])

The spread syntax causes each element of the array to become a separate argument, so this is equivalent to

console.log(1, 2, 3)

which prints each number separately on the console.

To get [1, 2, 3] you shouldn't use ..., just write

console.log(a.shift())

To get 1,2,3 use

console.log(a.shift().join(','))
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

console.log(...a.shift())

is run in given order:

  1. a.shift() returns [1, 2, 3] => console.log(...[1, 2, 3])
  2. ...[1, 2, 3] is evaluated into 1 2 3 and passed to console.log as 3 different arguments => console.log(1, 2, 3)

Which has out of 1 2 3

  • "*`...[1, 2, 3]` is evaluated into `1 2 3`*" - it's unclear what you mean by `1 2 3`. Is that supposed to represent a string? Something else? – Bergi Sep 26 '19 at 22:25
  • not a string. its evaluated into three integer values (so to say) – Kerim Berdimyradov Sep 26 '19 at 22:53
  • Well, so to say, no. The `...` is not an operator, it doesn't evaluate to anything at all - it's simply part of the function call syntax. – Bergi Sep 26 '19 at 22:55