JavaScript methods categories you must knowπ§΅
Well, we all agree that Javascript is King and Js methods are part of essential concepts you can hardly avoid using, the sooner and better you understand them the easier your debug life becomes. Letβs get to the chaseπβ¦
First thing first, there are two major categories of methods in JavaScript mutating and Iterating non-mutating methods
1. Mutating,
Mutating array methods will change the original array.
i. push()
The push() method as its name suggests inserts an element at the end of an array.
let animals = [π,π,π]animals.push(π©)console.log(animals)
//Expected Output: [π,π,π,π©]
ii. pop()
The pop method will remove the last element from the end of an array
let animals = [π,π,π,π©]animals.pop()console.log(animals)// [π,π,π]
iii.unshift()
The unshift method will insert an element at the beginning
let animals = [π,π,π]animals.pop(π©)console.log(animals)// [π©,π,π,π]
iv.shift()
The shift method Remove first element(the zeroth index element) from an array
let animals = [π©,π,π,π]animals.pop()console.log(animals)// [π,π,π]
v. reverse()
The reverses method will reverse an array, the first element becomes last and the last element becomes the first.
const array = [1οΈβ£, 2οΈβ£, 3οΈβ£];array.reverse()console.log(array)// [3οΈβ£, 2οΈβ£,1οΈβ£];
vi.sort()
The sort method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending.
const months = [βMarchβ, βJanβ, βFebβ, βDecβ];months.sort();console.log(months);// expected output: Array [βDecβ, βFebβ, βJanβ, βMarchβ]
2. Iterating
This is a group of methods that do not mutate the original array but iterates through the array.
i. forEach() calls the function provided once for each element
arr = [π₯π₯π₯π₯]
[π₯π₯π₯π₯].forEach((π₯)=>{
hatch(π₯)
})//expected outputs
//π£
//π£
//π£
//π£
console.log(arr)//[π₯π₯π₯π₯]
ii. slice() this method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included)
const animals = [π, πΊ, π«, π¦, π]console.log(animals.slice(2))// expected output: [π«, π¦, π]
iii. concat() this method appends one or more arrays with a given array, the method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array.
const g = [ππ π]const b = [πΊπΊπΊ]const bng = g.concat(b)console.log(bng)//[πππ, πΊπΊπΊ]
These are just a few examples of the array methods that you will often come across as you learn JavaScript, would you like to learn more? I will be sharing a lot of beginner-friendly content and insights on my Twitter timeline, you can follow me at @justinecodez