JavaScript Array | Example, and List of Methods

JavaScript array has more than one value at a time. In another word you can say an Array is a collection of similar types of elements.

Note: Array index is starts 0.

Syntax

Declaring an Array

Creating an Array

Example JavaScript Array

Creating Array with values.

Output:

Example JavaScript Array

Using the JavaScript Keyword new

Output: a,b

Advantage of Array

  • JS Arrays represent multiple data items of the same type using a single name.
  • In arrays, the elements can be accessed randomly by using the index number.

List of JavaScript array methods

Arrays provide a lot of methods. A cheat sheet of array methods in JavaScript:

  • To add/remove elements:
    • push(...items) – adds items to the end,
    • pop() – extracts an item from the end,
    • shift() – extracts an item from the beginning,
    • unshift(...items) – adds items to the beginning.
    • splice(pos, deleteCount, ...items) – at index pos delete deleteCount elements and insert items.
    • slice(start, end) – creates a new array, copies elements from position start till end (not inclusive) into it.
    • concat(...items) – returns a new array: copies all members of the current one and adds items to it. If any of items is an array, then its elements are taken.
  • To search among elements:
    • indexOf/lastIndexOf(item, pos) – look for item starting from position pos, return the index or -1 if not found.
    • includes(value) – returns true if the array has value, otherwise false.
    • find/filter(func) – filter elements through the function, return first/all values that make it return true.
    • findIndex is like find, but returns the index instead of a value.
  • To iterate over elements:
    • forEach(func) – calls func for every element, does not return anything.
  • To transform the array:
    • map(func) – creates a new array from results of calling func for every element.
    • sort(func) – sorts the array in-place, then returns it.
    • reverse() – reverses the array in-place, then returns it.
    • split/join – convert a string to array and back.
    • reduce(func, initial) – calculate a single value over the array by calling func for each element and passing an intermediate result between the calls.
  • Additionally:
    • Array.isArray(arr) checks arr for being an array.

Q: How to get the JavaScript array length?

Answer: Using the length property you can get the length of an array (the number of array elements).

Output: 4

Do comment if you have any doubts and suggestion on this topic.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.