Commonly Utilized JavaScript Methods Part III - Loops

Welcome back to the Commonly Utilized JavaScript Methods series, this segment is regarding the use of Loops to fully grasp methods and technique pertaining to JavaScript are essential and integral to understand for they provide convenience and simplicity to operation of algorithms to run a program optimally and smoothly.

What are Loops?

Loops essentially iterate data structures such as Array elements, under conditions. Iteration is not to be confused with Iteration method albeit it is what a loop consists of. There are a plethora of types of Loops in JavaScript and the most common ones utilized are the: For Loop, For In Loop, For Of Loop, While Loop and Do...While Loop. The remainder of this article shall breakdown what the basis and purpose of each loop is, benefits of them and how they differ from each other as well as Iteration methods.

What is a For Loop?

A For Loop is made up of 4 major components for it to be ran, which is the:  Initialization/initializer: a variable that is typically set via let indicating which index of a string or array to iterate from. For example let i = 0 which essentially mean start from index 0. Next component is the Condition:  this is responsible for the validation of whether the test being ran returns true, for cases of being true the loop continues, otherwise the loop breaks.  Next is the Final expression which determines whether you loop incrementally or at a decrement via i++ or i--  and lastly is Statement: code to be repeated in the loop as well as result to be displayed via console.log().

Imagery of Breakdown:

for ([initialization]); [condition]; [final-expression]) {
// statement
}

Example of For Loop iteration of a string:

//Example #1 - iteration of string:
//Checking age of elephant with increment increase by +=2:
for (let elephant = 1; elephant < 10; elephant += 2) {
if (elephant === 7) {
break;
}
console.info("elephant is " + elephant);
}
//Results: elephant is 1, elephant is 3, elephant is 5.

Example of For Loop iteration of an array:

//Example #2:
//Iteration through an array:
let footballJerseyNumbers = [44, 4, 33, 27, 36, 4];
for (let i = 0; i <= footballJerseyNumbers.length - 1; i++) {
//array.length -1 eradicates return of undefined:
console.log(footballJerseyNumbers[i]); // return each element
}
/*
Results:
44
4
33
27
36
4

*/

Example of Nested For Loop:

//Example #3 - Nested For Loops:
const nestedArray = [
[2, 4],
[6, 8],
[10, 12],
];

//nested loop:
for (let i = 0; i < nestedArray.length; i++) {
for (let j = 0; j < nestedArray[i].length; j++) {
console.log(nestedArray[i][j]);
}
}

/*

Results:
2
4
6
8
10
12

*/

Pros and Cons of For Loop:

For Loops are optimal for iteration through elements of an array or string, it can also iterate multidimensional arrays via use of nested loops. The perils of utilizing For Loops it is integral to know the length of the array especially appending .length -1 to avoid returning undefined at the end of iteration. For breaking out of a loop after a specific condition it's important to create a conditional statement with a break in it.

What is the For In Loop?

This loop is utilized to iterate over objects built via array or object constructors, and the properties of the objects via execution of inside block of code are checked once. For In Loops are optimal for the debugging of Objects and data structures that utilize key and pair values instead of arrays. For the iteration and debugging of arrays it is far more better to utilize forEach or for loop instead.

Imagery of Breakdown:

for (variable in object) {
statement;
}

Example of For In Loop to return property, key and value:

//Example #1 - return string of property, keys and values:
let threeObject = { a: 3, b: 6, c: 9 };

//for in loop:
for (const property in threeObject) {
//return the key and value of the property in object:
console.log(`threeObject.${property} = ${threeObject[property]}`);
}

/*

Results:
threeObject.a = 3
threeObject.b = 6
threeObject.c = 9
*/


Example of For In Loop implementing hasOwnProperty():

//Example #2 - implement hasOwnProperty():
let plainSquare = { a: 1, b: 2, c: 3, d: 4 };

function ColouredSquare() {
this.color = "blue";
}

//set new object with function above:
let newObject = new ColouredSquare();

for (const property in newObject) {
if (newObject.hasOwnProperty(property)) {
console.log(`newObject.${property} = ${newObject[property]}`);
}
}

/*
Result:
newObject.color = blue
*/

Pros and Cons of For In Loop Usage:

As mentioned prior the For In Loop is optimal for the iteration of objects for return key and pairs, it can also add, delete and modify property although this is a capability of the method it can also be deemed as a peril. Due to the fact deleted and modified properties are not revisited until after the iteration is completed. Another disadvantage of the For In Loop is only exclusively for Objects and not other data structures such as Arrays.


What is the For Of Loop?

For of Loop is capability of iteration over stringsarrays as well as arguments, nodeLists, TypedArrays, Maps and SetsFurthermore, displaying more versatility than other loop counterparts.

For of Loop enables programmers to implement custom hooks/statements to obtain and display distinct properties of objects. Components of the For of Loop includes: variable, iterable and lastly the statementVariable can be set as const let or var (out-dated), the variable being set is integral to identifying which property is being evaluated and executed during the loop. Iterable is the object that contains the elements/properties begin looped through for instance if an array is declared as const newNumbers = then newNumbers is the iterable. 


Imagery of Breakdown:

for (variable of iterable){
statement.
}

Example of For Of Loop with Arrays:

//Example #1 - iterating over an array:
const newNumbers = [20, 40, 60, 80];

for (const value of newNumbers) {
//returning the values of the array:
console.log(value);
}
/*

Result:
20
40
60
80

*/

//Example #2 - iterating over an array returning strings via element:
const favAdjectives = ["Sublime", "Prestigious", "Iconic", "Exuberant"];

//for of loop:
for (const element of favAdjectives) {
console.log(element);
}
/*


Results:
Sublime
Prestigious
Iconic
Exuberant

*/

Example of For Of Loop with Strings:

//Example #3 - iterating over string:
const cheeseString = "Cheddar";

//for of loop:
for (const value of cheeseString) {
console.log(value);
}
/*

Results:
C
h
e
d
d
a
r

*/

Examples of For Of Loop with Arguments Object:

//Example #4 - iterating over Arguments object:
function returnObject() {
for (const n of arguments) {
console.log(n);
}
}
console.log(returnObject(4, "Black")); //Results: 4 Black

//Example #5 - iterating over Arguments object:
(function () {
for (const argument of arguments) {
console.log(argument);
}
});
4, 8, 12; //Results: 4, 8, 12

Examples of For Of Loop with Map:

//Example #6 - iterating over Map:
let dorasMap = new Map();
dorasMap.set(1, "Grandma's House");
dorasMap.set(2, "Swiper's Lair");
dorasMap.set(3, "Pot of Gold");
dorasMap.set(4, "Aligator Swamp");

//for of loop:
for (const entry of dorasMap) {
//statement:
console.log(entry);
}
/*

[ 1, "Grandma's House" ]
[ 2, "Swiper's Lair" ]
[ 3, 'Pot of Gold' ]
[ 4, 'Aligator Swamp' ]

*/

//for of loop to obtain only value:
for (const [key, value] of dorasMap) {
console.log(value);
}

/*

Examples of For Of Loop with Set:

//Example #7 - iterating over Set:
const setsOfTwos = new Set([2, 2, 4, 4, 6, 6, 8, 8]);

//for of loop:
for (const value of setsOfTwos) {
console.log(value);
}
/*

Results:
2
4
6
8

*/

Pros and Cons of For Of Loop Usage:

It is quite evident of the versatility of the For Of Loop usage but a detriment of using this method, is due the inability to determine initiate and where to end the iteration.

What is a While Loop?

The while loop is ran via evaluation of the condition, when the condition is true then the statement or statements are ran. For instances of condition being false then the loop ends.

Imagery of Breakdown:

while (condition)

{

statement(s);

}

Examples of While Loop:
//Example #1 of while loop:
let indexOne = 3;
while (indexOne < 12) {
console.log(indexOne);
indexOne++;
}

/*

Results:
2
4
6
8
3
4
5
6
7
8
9
10
11

*/

// Example #2 of while loop - push iteration to Array:
let whileArray = [];

//set variable to iterate:
let index = 0;
while (index <= 8) {
whileArray.push(index);
index++;
}
console.log(whileArray);
/*

Result:
[
0, 1, 2, 3, 4,
5, 6, 7, 8
]

*/


What is Do... While Loop?

The Do While Loop objective is to ensure the code is executed at least once, for instances of the condition inside to the while block being true, the iteration proceeds. For cases of being false the loop is terminated/ceased.

Imagery of Breakdown:

do {

//statement(s)

} while (//condition);

Examples of Do While Loop:

//Example #1 of do while loop:
let iterableElement = 0;

do {
iterableElement = iterableElement + 1;
console.log(iterableElement);
} while (iterableElement < 5);

/*

Results:
1
2
3
4
5

*/

//Example #2 of do while loop store results in an array:
let resultsArray = [];
let newIterable = 0;

do {
newIterable += 1;
resultsArray += newIterable + " ";
} while (newIterable > 0 && newIterable < 5);

console.log(resultsArray); //1 2 3 4 5



This concludes this article, the next entry shall cover TypedArray, Map, and Set.


Comments

Popular Posts