What is a loop?
Loops are a sequence of instructions that is continually repeated until a certain condition is reached. In short, they are used to do repetitive task
Types of JavaScript loop
for loop
for...in loop
for...of loop
while loop
do while loop
Key concepts
initialization
condition
updation
for
This traditional loop will be found mostly in every programming language. It accepts maximum 3 arguments initialization
, condition
and updation
// syntax
for(initialization, condition, updation){
// statements to be executed
}
// example
for(let i = 1 ; i < 5 ; i++){
console.log(i)
}
/* output :-
1
2
3
4
*/
for..in
A special loop which is used to enumerate over the properties of an object.
// syntax
for(variable in object){
//statements
}
// example
const obj = {
name : "raj",
className : "12th"
}
// class is a reserved word that's why i used className
for(let i in obj){
console.log(i)
}
/* output :-
name
className
*/
// to get the key's value
for(let i in obj){
console.log(obj[i])
}
/* output :-
raj
12th
*/
Important consideration for for..in
loop
This loop is designed only for the objects and hence Arrays are also an object in JavaScript but that does not mean we can use
for..in
loop to iterate the keys or index of array elements. As it is not guaranteed thatfor..in
loop results the correct if used over arrays.The
for..in
loop does not guaranteed the exact order of the keys, as declared while creating an object. It may vary according to the nature of object and engine's implementation of JavaScript. Thefor..in
loop says if you need the exact order of object then use different loop structure or consider adding logic to sort them out.// example showing order of the keys const obj = { a : "A", b : "B", 1 : "one", 2 : "two" } for(let i in obj){ console.log(i) } /* output -> 1 2 a b */
It may seen not good but that is the behaviour of
for..in
loop. you can see that numeric keys are displayed first.
Why for..in
are not recommended for arrays
consider having an array [1,2,3]
and we are adding meta data or additional information about the array. since array are objects too so they support adding using dot notation. consider adding .customproperty
in array.
Well, doing this so can create uncertainty as for...in
will provide inappropriate results.
let arr = [1,2]
arr.customProperty = "name"
console.log(arr.length) /* length is a property that return the length
of array. in this case it will print 3 (starting from 1) */
for( let i in arr){
console.log(i) // return the indexes (starting from 0)
}
/* output
3
0
1
customProperty
*/
If this has to be done then avoid using array for that instead use Objects that can separate indexed and non-indexed elements.
for...of
• The for..of
loop is specially designed for iterating over the iterable data structure like arrays and strings etc.
• It provides a more readable and concise way to loop through the elements of an iterable without the need for explicit indexing or managing loop variables.
// syntax
for (variable of dataStructure){
//statement
}
// example of array
let arr = [1,2]
for(let i of arr){
console.log(i)
}
/* output ->
1
2
*/
// example of string
let string = "hehe"
for(let i of string){
console.log(i)
}
/* output ->
h
e
h
e
*/
More on for...of
Comparison
for...of
loop is used to retrieves value from the iterable data structure while the for...in
retrieves the property name or keys from the object.Appropriate use of for...of
for...of
is generally more appropriate for arrays and other collections because it ensures that you're iterating over the elements in the intended sequence without including unexpected properties or prototype keys.Use case
Arrays
A more straightforward and cleaner way to iterate over array elements. Strings
To iterate over individual characters in a string. Sets
To loop through unique value. Map
To iterate over ey-value pairs.Consideration
while
• The while loop continue to run until the condition becomes false. It is an entry control loop where the loop run only when the condition is true. However, it is necessary to note that sometimes while loop results in endless loop. So make sure to give correct updation value.
• It is commonly used when the number of iteration is not known in advance
// syntax
initialization
while( condition ){
//statements
updation
}
// example
let i = 5
while( i > 1 ) {
console.log(i)
i--
}
/* output ->
5
4
3
2
*/
do while
It is a loop that will run at least one time even if the condition is false because the condition will check in the end of this loop.
A
`;`
is mandatory at the end of condition
// syntax
let i = 5
do {
console.log(i)
} while ( i > 10);
// output -> 5
/* The condition is false but it will run atleast one time
and after that if the condition unsatisfied the criteria then it will
exit from the loop.
*/
Congratulations!!!!!! You have learned loops in JavaScript ( vo bhi in depth) .......
If you want more such content then make sure to following me on all available platform
Thank you for reading 🤍
Written By Mohit Soni