console.log(myArray) VS console.log(myArray.shift())

Tell us what’s happening:
In this example below console.log(myArray.shift()) returns [“dog”, 3]
But console.log(myArray) returns [[“dog”, 3]]
So if we would have nothing left in myArray we would have :
console.log(myArray.shift()) returns undefined
and console.log(myArray) returns
Should we consider it a the same result in both cases , why having extra brackets for myArray while myArray.shift() is supposed to return the exact result (same type) as myArray.
Your code so far


// Setup
var myArray = [["John", 23], ["dog", 3]];

// Only change code below this line
var removedFromMyArray;
removedFromMyArray = myArray.shift();
console.log(removedFromMyArray);
console.log(myArray.shift())
console.log(myArray)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.74.

Challenge: Manipulate Arrays With shift()

Link to the challenge:

The shift method returns the removed item (what was in the first index)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

The return value of a function call is what is logged.

I mean in case myArray = [[1,2] , [3 ,4]] is a nested array ,
then myArray returns [[3, 4]]
But myArray.shift returns [3, 4] without extra brackets
Also if after using .shift and myArray is Empty, then myArray returns [ ] but myArray.shift returns undefined
As I understand myArray.shift and myArray should return the exact same value after removing the first element

removedFromMyArray = myArray.shift(); // removes John
console.log(removedFromMyArray); // displays John
console.log(myArray.shift()); // removes and displays dog
console.log(myArray); // displays empty array
console.log(myArray.shift()); // removes and displays nothing, which JavaScript calls 'undefined'

Logging the array and logging the result of shifting an element off of the array should always do different things.

1 Like

Many thanks for your answer :grin:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.