It is the second article from the polyfill series. If you haven't read the previous article on the polyfill of the array push method then you can find that article here Push Polyfill.
Today we will learn about the polyfill of the array pop method.
The behavior of the already existing method
Let us first see how the pop method works in javascript.
It is used to remove one element from the end of the array and returns the value of the deleted item from the array.
CASE 1: let array = [1,2,3,4];
console.log(array.pop());
//RESULT
4
CASE 2: let array = []; //array can be empty
console.log(array.pop());
//RESULT
undefined
CASE 3: let array = ""; //value other that array
console.log(array.pop());
//RESULT
TypeError: array.pop is not a function
CASE 5: let object = {
length: 3,
random: "boo",
2: 5,
}; //using object
console.log(Array.prototype.pop.call(object));
console.log(object)
//RESULT
5
{
length : 2, //total length
random : "boo" //already existing key
}
Let's create our custom pop method now
//Whenever we will call [].customPop()
//this -> []
function customPopMethod()
{
//First we will check the type of this
if(this === null || this === undefined)
{
throw new TypeError('.pop is not a function')
}
}
Array.prototype.customPop = customPopMethod;
function customPopMethod()
{
//First we will check the type of this
if(this === null || this === undefined)
{
throw new TypeError('.pop is not a function')
}
//Now if we know this is a type of
// object or array, we will find the length
let length = this.length || 0;
if (!length) return undefined;
}
function customPopMethod()
{
//First we will check the type of this
if(this === null || this === undefined)
{
throw new TypeError('.pop is not a function')
}
//Now if we know this is a type of
// object or array, we will find the length
let length = this.length || 0;
if (!length) return undefined;
let poppedElm = this[length - 1]; //Getting the last element from this
delete this[length - 1]; //deleting the last element from this
this.length = length - 1; //decreasing the size of this
return poppedElm; //returning the popped element
}
Let's check the output of the custom pop method
CASE 1: let array = [1,2,3,4];
console.log(array.customPop());
//RESULT
4
CASE 2: let array = []; //array can be empty
console.log(array.customPop());
//RESULT
undefined
CASE 3: let array = ""; //value other that array
console.log(array.customPop());
//RESULT
TypeError: array.pop is not a function
CASE 5: let object = {
length: 3,
random: "boo",
2: 5,
}; //using object
console.log(Array.prototype.customPop.call(object));
console.log(object)
//RESULT
5
{
length : 2, //total length
random : "boo" //already existing key
}
Hope you enjoyed reading, learning and implementing array pop polyfill.
If you enjoyed then support by liking and commenting your views.
We will meet with another polyfill, till then Goodbye :-)