Traversing Data In Javascript
Data Structures are a huge part of any application. They are used intensely in the world of programming. Hence a programmer's most time is spent creating algorithms using data structures. Knowing how to access or traverse data is definitely going to come in handy. This is exactly what we are exploring in this blog post.
For Loop
Let's see how we can access iterable data structure using a traditional for loop.
const arr = ["zero", "one", "two", "three", "four", "five"];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
//This is how we access every element of the array
}
A for
statement looks as follows:
for ([initialExpression]; [conditionExpression]; [incrementExpression])
statement
When To Use Traditional For Loop
The traditional for loop give you immense control over the iteration. A traditional for loop should be preferred in following situations:-
When you want to start iteration at some specific index
You can chose the from where to start the iteration i.e.,initial counter
const arr = ["zero", "one", "two", "three", "four", "five"];
for (let i = 3; i < arr.length; i++) {
console.log(arr[i]);
//This will start printing from third index onwards
}
When you want to increment the counter according to your preference
Consider a situation where you want to access elements according to some criteria. For example to select elements only at even index would look like following
const arr = ["zero", "one", "two", "three", "four", "five"];
for (let i = 0; i < arr.length; i+=2) {
console.log(arr[i]);
//This will print elements only at even indices
}
When you want to exit the loop at some point
Consider a situation where you want to iterate until certain criteria is fulfilled. For example - Searching! Suppose you are traversing an array to search for an element. You happen to find it, so now that you have found the element, doesn't it make sense to come out of the loop instead of traversing further
const arr = ["zero", "one", "two", "three", "four", "five"];
for (let i = 0; i < arr.length; i++) {
if(arr[i] === "three"){
console.log("Breaking out of the loop");
//At this point, we will break out of the loop
//won't move forward to rest of the indices
}
}
For-In Loop
The for-in loop always loops over an object’s elements one by one. These names can be array indexes or key-value pairs. The syntax:
for (let i in object) {
console.log(object[i]);
}
const student = {
name: "Nikhil",
last_name: "Sharma",
school: "KV JNU",
university: "Gautam Buddha University",
};
for (let key in student) {
console.log(key);
//prints keys from the object
}
/*
OUTPUT
name
last_name
school
university
*/
If the object is an array, the for-in loop will print out the array indexes in order. If the object contains key-value pairs, the for-in loop will print out each key that exists.
for-in is not a good choice for looping over Arrays:
- It visits property keys, not values.
- As property keys, the indices of Array elements are strings, not numbers
- for-in skip empty elements in the array.
For-Of Loop
The for...of statement creates a loop Iterating over iterable objects (including Array, Map, Set, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
const arr = ["red", "blue", "green"];
for (let value of arr) {
console.log(value);
//prints value in array
}
/*
OUTPUT
red
blue
green
*/
Points to note
- If the object is an array, the for-of loop will print out the values of the array’s indexes in order.
- If the object contains key-value pairs, the for-of loop will print out every value that exists.
- for-of does not skip empty elements in the array.
Array.prototype.map()
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
const arr = ["red", "blue", "green"];
arr.map(value => console.log(value));
/*
OUTPUT
red
blue
green
*/
Points to note
- Array.map() returns a new array
- Like for loop you can't determine the initial counter, termination-counter, increment. Array.map() will iterate through each and every element without skipping.
- You can't exit out of the loop like break in for-loop.
forEach() loop
The forEach() method executes a provided function once for each array element.
const arr = ["red", "blue", "green"];
arr.forEach((value, index) => {
console.log(index, value);
});
/*OUTPUT
0 red
1 blue
2 green
*/
Points to note
- for-each skip empty elements in the array.
- You can't break out of the for-each loop using break.