The Array is one of the most common data structures we have in the program. In JavaScript, there are many ways to manipulate an array, and all JavaScript programmers should be familiar with these.

For any type of data structure, the most common operations are to traverse the collection, query elements, modify elements, add and remove elements. Arrays are no exception, so I will focus on these operations to introduce tips of arrays.

Loop an array

Iterating through arrays is one of the most common requirements, so do you know how many ways to iterate through an array?

for index

First, arrays are indexed data structures, so we can iterate over arrays by indexing.

let array = ['a', 'b', 'c', 'd']

for(let i = 0; i < array.length; i++) {

for of

In JavaScript, Array is a data structure with an Iterator interface. For such a data structure, we can traverse through for … of. This is the best way to iterate over arrays if we don’t need its indexes.

let array = ['a', 'b', 'c', 'd']

for(let element of array) {

for in

If we want to walk through a normal object, we can use the for in syntax to get the key and value of the object.

let obj = {key1: 'value1', key2: 'value2'}
for(let key in obj){
  console.log(key, obj[key])

In JavaScript, all arrays are objects, so we can apply this to arrays as well. In this case, the index is the key to the object.

let array = ['a', 'b', 'c', 'd']

for(let index in array) {
  console.log(index, array[index])

#programming #javascript #coding #web-development

16 Tips for Array in JavaScript that Every Beginner Should Know
24.95 GEEK