Why does this spread operator output unexpected values?

63 Views Asked by At

const arr = [7, 8, 9];

const badArr  = [1, 2, arr];

const newArr = [1, 2, ...arr];

console.log('Bad array: ' + badArr);
console.log('Good array: ' + newArr); 

I was expecting [1,2,[7,8,9]] for the badArr, instead I got the same return of [1,2,7,8,9]. Is this something newer in JS? (Completing an older course).

1

There are 1 best solutions below

0
Leau On

The + operator between a String and an Array is a concatenation, your Array is stringified and appended to your debug String when you log it.

Your variables contain the intended values anyway.

What can you do to avoid this:

const arr = [7, 8, 9];

const badArr = [1, 2, arr];

console.log('Bad result: ' + badArr); // returns String
console.log('Good result: ', badArr); // returns String and Array