Example 1
I have a code pushing one spreaded array into another:
const hobbies = ['Sports', 'Cooking'];
const activeHobbies = ['Hiking'];
activeHobbies.push(...hobbies);
console.log(activeHobbies); //['Hiking', 'Sports', 'Cooking']
hobbies.push('Skiing');
console.log(hobbies); //['Sports', 'Cooking', 'Skiing']
console.log(activeHobbies); //['Hiking', 'Sports', 'Cooking']
Is a spreaded array pushed same as activeHobbies.push(hobbies[0], hobbies[1])
by values?
Why is it not ['Hiking', 'Sports', 'Cooking', 'Skiing']
in the last line ?
Example 2
const hobbies = ['Sports', 'Cooking'];
const activeHobbies = ['Hiking'];
activeHobbies.push(hobbies);
console.log(activeHobbies); //['Hiking', ['Sports', 'Cooking', 'Skiing']], why not ['Hiking', ['Sports', 'Cooking']] ?
hobbies.push('Skiing');
console.log(hobbies); //['Sports', 'Cooking', 'Skiing']
console.log(activeHobbies); //['Hiking', ['Sports', 'Cooking', 'Skiing']]
As I understand, hobbies
array will be pushed to activeHobbies
by reference without spreading like this activeHobbies.push(hobbies)
and the new values will be added to hobbies
array inside activeHobbies
array, if new values are pushed to hobbies
array, because it’s pushed by reference. Is it correct?
But why the first console outputs ['Hiking', ['Sports', 'Cooking', 'Skiing']]
and not ['Hiking', ['Sports', 'Cooking']]
?