As part of my Knowledge is Power series, I aim to post once a week about something I've learned. This week one of the things I've learned about is Arrays.
Arrays are a comprehensive and powerful tool in JavaScript and there are so many ways to use them to your advantage. I hope to simplify some Array functions so that it's easier for all of us newbies to understand!
Array.push()
The push() method simply adds an element to the end of the array and increases its length. It's not limited to one element, you can add more than one simply by adding a comma and another element.
See below:
Array.pop()
The pop() method does the opposite of what push() does at the end of the array, it simply 'pops' what's at the end and removes it (only one element at a time).
See below:
Array.unshift()
The unshift() method adds an element to the beginning of the array and increases its length. It's not limited to one element, you can add more than one simply by adding a comma and another element.
See below:
Array.shift()
The shift() method 'shifts' an element (at a time) from the beginning of the array and removes it.
Array.map()
Things are getting interesting, the map() method creates a new array with the results of calling a function.
Check this; the function runs on every element within the array.
See below:
Array.some()
The some() method tests whether at least one of the elements in the array passes the test within the called function.
See below:
Array.every()
The every() method tests if all the elements in the array pass the test within the function - it returns a Boolean value.
In the below example, you can see it returns false but do you know which number is causing it to return false?
Array.find()
You don't need to find which number is causing it to return false, just use the .find() method! The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no value satisfies the testing function, it will return undefined
.
These are just some of the array methods out there but these are just the ones that I've been exposed to over the last few days.
Because you got down this far, enjoy this visualisation of some array methods that I put together, it made me chuckle.
If you're still reading, thank you so much, I hope to use this blog to post and share useful information I gain! I would love to connect with other developers to see what they're learning and learn from them - please connect with me on the following:
Twitter: @codewithmohamed
Github: github.com/codewithmohamed
LinkedIn: Mohamed Mohamud
Email: m.mohamud1992@gmail.com