Back to questions
JuniorTheoryCommon
What does the program print?
const a = [1, 2];
const b = a;
b.push(3);
console.log(a.length, a === [1, 2, 3]);3 false
- Expecting
b = ato copy the array: both names point to one array, sob.push(3)changesatoo anda.lengthis3. - Expecting
===to compare the elements: for arrays it checks whether both sides are the same array, and[1, 2, 3]is a new one, so it isfalse.
- How would you make
ba separate copy so thatakeeps two elements? - What does
a === bprint, and why?