xxq xxq - 1 year ago 83
Javascript Question

How to retrieve the first item in an array in javascript?

I am new to javascript. I am doing a task which trying to get the first item removed from an array in javascript.

Method One

function getFirst(arr, item) {
var removed = arr.shift();
return removed;

Method Two

function getFirst2(arr, item) {
arr = arr.push(item);
var removed = arr.shift();
return removed;

I comes out with these two solution but only method one accepted and method two is the wrong one which return Uncaught TypeError: arr.shift is not a function().

What is the extacly meaning of Uncaught TypeError and state that arr.shift is not a function but it works on Method one?

Any help will be appreciate! Thanks!

Answer Source

Your function getFirst2() is not working because of arr = arr.push(item). Here arr actually becomes a number, as the push method on an array returns the new length property of the object upon which the method was called.

Thus calling method push on a number throws a TypeError.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download