arr.push(item);
var item=arr.shift();
return item;
my question is why anyone havn’t use shift() function to add item in the beginning?
i mean we can if not used return statement then can we use this like arr.shift(); ?
That would be a 'Cut in Line" lesson, rather than a stand in line one.
Think of it as a stack of orders in a diner - orders get added to the end of the list but get handled from the beginning of the list. Otherwise, your first diners in would never get handled, and see everyone who came in after them eating while they’re still waiting!
sorry instead of shift() i had written unshift but my question is still the same we can use that function and for that we don’t even need to a return statement, if not then why?
Sir, I got the question but my question is about using shift() operator i am not understanding ,because when i had first tried to solve this challenge i have used arr.push();
arr.shift();
I guess I’m not quite getting the question. Array.push and array.pop are the functions to add to or remove from the end of the array, while array.unshift and array.shift add to and remove from the beginning of the array.
So in this case we push to add to the end, then shift to remove from the beginning.
yes “So in this case we push to add to the end, then shift to remove from the beginning.”
exactly this is what i am saying why there is no use of shift for removing element in the second part of the question.?
see functions are used for reducing code and basically code duplication and make it efficient and when we have already function to remove beginning element then what is the need to assign it item or any other variable ?
suppose this code is small that’s why we easily dont’t thinking about that but what if there is more than one statement in console.log or in that function then ?
Ahhhh and you’re right. We could have avoided the variable and simply return arr.shift() for the exact same result, with the added benefit of not using a 'throwaway variable."
That’s some good thinking, partof a collection of rules referred to as “the elements of javascript style” in some circles.
Both approaches are valid, but you’re completely correct that finding ways to minimize unnecessary variables is good practice, so kind as your code remains readable.
In This case, i prefer your solution. It explicitly says what it’s returning, rather than having to find what item references somewhere in your code. Short code, but still it is explicit.