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?
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?
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(','))
console.log(...a.shift())
is run in given order:
a.shift()
returns [1, 2, 3]
=> console.log(...[1, 2, 3])
...[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