Array Methods in JavaScript
Mastering arrays is essential for any developer. Here is a quick guide to the most common array methods in JavaScript.
Managing Length and Content
- length: Returns the number of items in an array. You can change this property to trim or extend an array.
- toString(): Converts an array into a single string. It does not change your original array.
- join(): Combines all elements into a string. You can choose a custom separator like a comma or a space. It turns null or undefined into empty strings.
- isArray(): A reliable way to check if a variable is an array.
Adding and Removing Items
- push(): Adds one or more items to the end of an array. It returns the new length.
- pop(): Removes the last item from an array. It returns the item you removed.
- unshift(): Adds items to the start of an array.
- shift(): Removes the first item from an array.
- splice(): Changes your array by removing, replacing, or adding new items. This modifies the original array.
- toSpliced(): Does everything splice does, but it creates a new array instead of changing the original one.
Accessing and Copying Data
- at(): A modern way to get items. Use negative numbers to count from the end. For example, .at(-1) gets the last item.
- slice(): Extracts a section of an array. It returns a new array and leaves the original alone.
- concat(): Joins two or more arrays into one new array.
- copyWithin(): Copies array elements to another position within the same array.
- flat(): Flattens nested arrays into a single level.
Iterating through Arrays
- forEach(): Runs a function for every single item in your array. It is great for simple loops.
Source: https://www.geeksforgeeks.org/javascript/javascript-array-methods/
Full Guide: https://dev.to/ezhil_abinayak_e38eec8fb/array-methods-in-javascript-1f5f
