JS For In Loop


For loop example:

var sum = 0;
for (var i=1; i<=100; i++)
{
	sum += i;
}
alert(sum); //5050


You may use break to jump out of the loop:

var sum = 0;
for (var i=1; i<=100; i++)
{
	if (i == 50) break; stop the loop if i=50
	sum += i;
}
alert(sum); //1225


You may use continue to skip 1 step of the loop:

var sum = 0;
for (var i=1; i<=100; i++)
{
	if (i == 50) continue;
	sum += i; //not executed if i=50
}
alert(sum); //5000


For loop used for array:

var arr = [2,4,5,8,1,3,9];
for (var i=0; i<arr.length; i++)
{
	if (arr[i] % 2 == 0) alert(arr[i]); //2,4,8
}


For In loop used for array:

var var = [2,4,5,8,1,3,9];
for (var i in arr)
{
	if (arr[i] % 2 == 0) alert(arr[i]); //2,4,8
}


endmemo.com © 2024  | Terms of Use | Privacy | Home