In the previous tutorial, we have seen about for loop with different examples. In this section, you will learn about for..in loop description, syntax, and with the help of different examples.
For..in loopThe javascript for..in loop is used to iterate in object properties.
Syntax
for (variable in object) { //Code to excute }
Example 1: Loop through an object.
<html> <head> <title>JS for..in loop</title> </head> <body> <script> var person ={fname:"Abebe",lname:"kebede",age:26}; var n; var x; for( n in person){ x=person[n]; document.write(n+"=>"+x+"</br>"); } </script> </body> </html>
fname=>Abebe
lname=>kebede
age=>26
Example 2: Display the sum of the salary of individuals.lname=>kebede
age=>26
<html> <head> <title>JS for..in loop</title> </head> <body> <script> var salary ={Abebe:8000, DG:7000, nahom:7500}; var n; var Total_sum=0; var x; for( n in salary){ Total_sum+=salary[n]; x=salary[n]; document.write(n+"=>"+x+"</br>"); } document.write("Total_Sum="+Total_sum); </script> </body> </html>
Abebe=>8000
DG=>7000
nahom=>7500
Total_Sum= 22500
Example 3: Iterate through strings.DG=>7000
nahom=>7500
Total_Sum= 22500
<html> <head> <title>JS for..in loop</title> </head> <body> <script> var string="DGTeck"; var s; var t; for(s in string){ t=string[s]; document.write(t+"</br>"); } </script> </body> </html>
D
G
T
e
c
k
G
T
e
c
k
0 Comments