𝗔𝗿𝗿𝗮𝘆 𝗠𝗲𝘁𝗵𝗼𝗱𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
Mastering array methods makes your code cleaner and faster. Here is a guide to the most common tools you need.
• Length and Basics Use .length to see how many items are in an array. You can even change the length to shorten an array. Use Array.isArray() to check if a variable is actually an array.
• Converting to Strings
- .toString() converts the array into a single string separated by commas.
- .join() gives you more control. You can choose your own separator like a space, a dash, or an empty string. It does not change your original array.
• Accessing and Adding Items
- .at() allows you to use negative numbers to grab items from the end. Use .at(-1) for the last item.
- .push() adds items to the end. It returns the new length.
- .pop() removes the last item.
- .unshift() adds items to the start.
- .shift() removes the first item.
• Modifying and Combining
- .concat() combines two arrays into a new one.
- .slice() picks a piece of an array without changing the original.
- .splice() changes the original array by adding or removing items at a specific index.
- .toSpliced() does the same as splice but keeps your original array safe by returning a new one.
- .copyWithin() copies part of an array to another location in the same array.
- .flat() turns nested arrays into one single array.
• Deleting and Iterating
- delete removes an item but leaves an empty hole in the array. The length stays the same.
- .forEach() lets you run a function for every single item in the list.
Use these methods to handle data efficiently in your projects.
Source: https://www.geeksforgeeks.org/javascript/javascript-array-methods/ Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join Full guide: https://dev.to/ezhil_abinayak_e38eec8fb/array-methods-in-javascript-1f5f
