Just like other loops while loops also repeat a code block inside while loops unless the given condition becomes true. The while loops takes condition insite let’s say we have created a counter starts from 0 we will use that like while(counter <= 9) so the loop will start repeating unless counter reached 9 and the counter will add 1 from the last line of code. Let’s create an array of programming languages then we will get its length using method of length javaScript.
Example of while loop.
[code lang=”js”]
<script type="text/javascript">
//declaring an array of ten students.
var p_lang = array("PHP", "JavaScript", "C++", "Java", "XHTML", "SQL", "CSS");
var condition = p_lang.length(); //getting length of array.
var counter = 0; //starting counter from 0
while(counter <= condition) {
document.write(p_lang[counter])+'<br>’;
counter++;
}
</script>
[/code]
We are starting counter from 0 cause first element of array indexed as 0 in javaScript array so if we have 5 elements in our array they would be indexed like 0 1 2 3 4 so four would be last index of the array element. In the last line of while loop we are using counter++ that will add 1 in the counter. That way if in start counter value is zero after first execution of this line will add 1 and counter value will become 1.