Wednesday, March 29, 2017

Learn JavaScript IV (Looping)

edankeun.com-looping in JS(JavaScript) use when you want to print out your code or give the repeat statement ,for example how to print number from 1 until 10 or how to print "Hello World" for 100 times,actually you can write that code manually but how if the program want to repeat 10000x times, how to do it? with Loop Statement can executed a block code in more time

Loop Method

  1. For Loop
  2. While Loop
  3. Do While Loop
1.For Loop Statement

For Loop usually used to create a loop

-example code

for(statement1;statement2;statement3){
   code for loop
}

statement1 : is executed before the loop running
statement2 : define the condition for running the loop
statement3 : to executed each time after the loop

Example



Explaination

var i is define the variable for i (numeric)
i<=10 loop the code less than equals 10 times
i++ to make variable i added with 1

example
var i=2;
result=i++;
document.write(result);

///Output 3


2.While Loop
while loop similar with For Loop but this statement will work if the condition is true

Example

While(Condition){
 code to loop
}

the result statement is always True or False
example



the loop will run as long as variable i less than 10 and don't forget to increase the value of variable i,
if you forget to increase the variable , the loop will do the infinite loop, and it will make the program error

3.Do While Loop
the different between while loop, this method will execute the codeblock once and check the condition on statement While

Example

Do{
 code block
}
while(condition)


Example


the code will executed once ,before check the condition
see the "Hello World" first,not show the number first because it's first executed


Conclusion
the summary is if you want to loop some codeblock , and you want to decide what the method will you used, it depend on what's the data that you used, and you have be careful if use the loop method, because can make the fatal Error ,for example is Infinite loop, the code will repeat infinite.

keep clean and Cheers !

Related Posts

Learn JavaScript IV (Looping)
4/ 5
Oleh