+ 1
Whats the logic behind this code snippet?? Wen I run it, it returns [3,6,9,3]
JavaScript Quiz 🏆 if you run this code what do you expect to see the output? const num = [ 3, 6, 9 ]; num.push(num.push(num.pop( ))); console.log(num);
4 Respostas
+ 3
When you see nested function/method calls like this, start working your way out from the inner most call, head out to the outer most call.
Knowing that ...
- pop() removes last item off an array, and returns the removed item.
- push() adds new item at the end of an array, and returns the updated array size.
So let's begin, initially <num> was [ 3, 6, 9 ].
Inner most call - num.pop()
Removes last item (9) and return the removed item (9) to the middle call. <num> then becomes [ 3, 6 ].
9 was passed off to the middle call - num.push()
Adds 9 back into <num> at the end, and return updated array size (3) to the outer call. <num> by then becomes [ 3, 6, 9 ] again.
3 was passed off to the outer call - num.push()
Adds 3 into <num> at the end, thus <num> becomes [ 3, 6 ,9, 3 ].
Then log array <num> in JS console.
+ 2
pop removes the last element of a list and returns the popped out element
push adds a element at the end of the list and returns the new length of the list
num.push(num.push(num.pop()));
// num = [3, 6]
num.push(num.push(9));
// num = [3, 6, 9]
num.push(3)
// num = [3, 6, 9, 3]
+ 1
Where did the last 3 comws fr0m??
+ 1
Rex Nerdy
Copy & paste this in Js tab of a new web code, may it help to understand
const num = [ 3, 6, 9 ];
console.log( `Originally, num = [${num}]\n` );
let result1 = num.pop(); // inner most call
console.log( `num.pop() removes ${result1} and returns ${result1}` );
console.log( `num = [${num}]\n` );
let result2 = num.push( result1 ); // middle call
console.log( `num.push() appends ${result1} and returns ${result2}` );
console.log( `num = [${num}]\n` );
let result3 = num.push( result2 ); // outer call
console.log( `num.push() appends ${result2} and returns ${result3}` );
console.log( `num = [${num}]\n` );