All about arrays in javascript

Harsh Vats on July 13, 2020

For beginners this article will be good lesson and for experts it would a good revision so that you don't google things again. After reading this article you won't encounter any problem related to javascript arrays.Let's consider there is an array, array = ['html', 'css', 'javascript'].

Acessing array

  1. array[1] will give you the element at index 1 which is "css".
  2. array[array.length - 1] will give you the last element if you don't know the length of the array.
  3. array.indexOf('css') will return the index of element 'css' which is 1.

Adding elements

  1. array.push('react') will add 'react' at the end of the array. You can add as many items as you want, just separate them with a comma.
  2. array.unshift('react') will add 'react' at the start of the array (i.e. at index = 0).You can add as many items as you want, just separate them with a comma.
  3. array.splice(2, 0, 'react') will delete 0 items starting from index 2 and then add 'react' at index 2.

Removing elements

  1. array.pop() removes the last element from array.
  2. array.shift() removes the first element from array.
  3. array.splice(1, 2) will remove 2 elements starting from index 1.
  4. array.slice(0, 1) will return a copy of portion of array (i.e. ['html', 'css'] in this case).

Looping through arrays

  1. array.forEach(item => console.log(item)) will loop through every element of the array.
  2. array.map() is similar to array.forEach() only difference being, map creates a new array and then perform opertations on it whereas forEach performs only the original array.

array.map() returns the new array with some operation applied on each element while array.forEach() returns undefined.

  1. array.filter(item => item.length > 3) will return another array with elements whose length is greater than 3.

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Connect with me on LinkedIn
© 2021, Built by Harsh Vats