JavaScript Arrays Methods - Part 1

An array is an object in JavaScript. Use it to store multiple values in one variable.

Instead of creating separate variables for every item, use one array.

Example: let students = ["John", "David", "Alex"];

Each value is an element. Every element has an index starting from 0.

• Index 0: John • Index 1: David • Index 2: Alex

Essential Array Concepts

  1. The length property The length property tells you the total number of elements. It is a property, not a function. Do not use parentheses.

• Correct: arr.length • Wrong: arr.length()

You can change the length to add or remove elements. If you decrease the length, JavaScript removes the extra elements. If you increase the length, JavaScript creates empty slots.

  1. toString() This method converts your array into a string. It joins elements with commas. It does not change the original array.

  2. join() Use this when you need a custom separator.

• fruits.join(" | ") returns "Apple | Orange | Banana" • fruits.join("-") returns "Apple-Orange-Banana"

  1. at() This method returns an element at a specific index. It supports negative numbers.

• arr.at(-1) returns the last element. • arr.at(-2) returns the second to last element.

  1. pop() This method removes the last element from your array. It returns the element it removed. This changes your original array.

  2. Array.isArray() Use this to check if a value is an array. The typeof operator returns "object" for arrays, so it is not reliable.

• Array.isArray([]) returns true • Array.isArray({}) returns false

  1. concat() Use this to merge two or more arrays. It does not change the original arrays. It returns a brand new array.

  2. copyWithin() This copies part of an array to a new position in the same array. It overwrites existing elements.

Important Note on delete The delete operator removes an element but keeps the array length the same. This creates an empty hole in your array. Use other methods if you want to remove elements and shrink the array.

Source: https://www.w3schools.com/js/js_array_methods.asp

Complete guide: https://dev.to/annapoo/javascript-arrays-methods-part-1-kb7