Austin Beaufort

Posted on

# Adding Methods to Prototypes, JS

Array.prototype.reverse()

.reverse() takes an array and reverses it:

``````const myNumbers = [1, 2, 3, 4, 5, 6, 7];

console.log(myNumbers.reverse()); // outputs [7, 6, 5, 4, 3, 2, 1];
``````

now lets pretend the .reverse() method doesn't exist

Let's make the method ourselves, we will call it .reverse2():

``````Array.prototype.reverse2 = function() {
const reversedArray = [];
this.forEach(item => reversedArray.unshift(item));
return reversedArray;
}
``````

If the above is confusing, here is the same thing but with comments for clarity:

``````Array.prototype.reverse2 = function() {
// create an empty array
const reversedArray = [];
// *this* reverses to the array to the left of the
// .reverse2() method, in our case, *myNumbers*.

// Here we take each item in myNumbers and add it to the front of reversedArray

// ex. [1], [2, 1], [3, 2, 1], etc...
this.forEach(item => reversedArray.unshift(item));
// return the reversed Array.
return reversedArray;
}
``````

Now we can use our .reverse2() method we created on any array:

``````const myNumbers = [1, 2, 3, 4, 5, 6, 7];
console.log(myNumbers.reverse2()); // outputs [7, 6, 5, 4, 3, 2, 1];
``````

still with me?

Here's the crazy bit.
.reverse() doesn't exist for strings 😱 😱 😱

``````const myString = 'I am writing a sentence';
console.log(myString.reverse()) // error, myString.reverse() is not a function
``````

Let's add .reverse() as a prototype method for Strings.

``````Array.prototype.reverse2 = function() {
const reversedArray = [];
this.forEach(item => reversedArray.unshift(item));
return reversedArray;
}

const myString = 'I am writing is a sentence'

String.prototype.reverse = function() {
return this.split('').reverse2().join('');
}

console.log(myString.reverse());
``````

A brief explanation:

1. we split the string every character:
['I', ' ', 'a', 'm'] ... etc.

2. The string is now an array, which means we can use our .reverse2() method we made for arrays. (or you can use the built in .reverse() array method here).
['e', 'c', 'n', 'e', 't', 'n', 'e', 's', ' ', 'a', ' ', 'g'] ... etc

3. We then join the array back together into a string:
**ecnetnes a gnitirw ma I"

Thanks for reading, for more tech content you can find me here:

Jon Randy 🎖️

Adding to native prototypes is generally a bad idea, unless you're doing it for polyfilling purposes

Austin Beaufort • Edited