JavaScript Arrays Methods - Part 1

An array is a special object in JavaScript. It stores multiple values in one variable.

Instead of creating separate variables for every student: let student1 = "John"; let student2 = "David";

Use an array: let students = ["John", "David", "Alex"];

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

• 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 resize your array.

  • Decreasing length removes elements from the end.
  • Increasing length creates empty slots.

• toString() and join() Use toString() to turn an array into a string separated by commas. Use join() when you want a custom separator like a hyphen or a pipe.

• The at() method This method returns an element at a specific index. Unlike bracket notation, it supports negative indexes. arr.at(-1) gives you the last element.

• The pop() method This removes the last element from an array. It modifies the original array and returns the removed item.

• Array.isArray() Use this to check if a value is an array. The typeof operator returns "object" for arrays, which is not helpful. Always validate your data with Array.isArray() before looping.

• delete vs concat() The delete operator removes an element but leaves an empty hole. It does not change the length. The concat() method merges arrays. It does not change the original arrays. It returns a new one.

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

Summary of methods:

  • length: Returns size.
  • toString(): Converts to comma-separated string.
  • join(separator): Converts to string with custom separator.
  • at(index): Gets element (supports negative index).
  • pop(): Removes last element.
  • isArray(): Checks if value is an array.
  • concat(): Merges arrays into a new array.
  • copyWithin(): Copies elements within the same array.

Source: https://www.w3schools.com/js/js_array_methods.asp Complete guide: https://dev.to/annapoo/javascript-arrays-methods-part-1-kb7