JavaScript – while and for loops


JavaScript has two loops, while and for. They both run at the same speed. The for loop is more flexible – it has three parts separated by semicolons in parentheses. General entry:

for(first; second; third);

Inside the parentheses, the semicolon is the delimiter, not the end of the line.

first – any instruction that the machine will execute once at the very beginning of the loop, for example, you can initialize a variable.

second – a condition similar to the conditions from the while loop; e.g. cat<2.

third – essentially the same as first; there may be a change in the counter; this part is executed each time at the end of the iteration of the loop.

Any of the three parts in the for loop can be omitted, it could look like this:

for( ; second; third);

for(first; ;third); etc.

To make the for loop similar to the while loop, it can be represented as follows:

varcat=2;
for( ; cat<11; );
{print(cat); cat++;}

An infinite loop in JavaScript using for looks like this:

for(first; ;third);

Those. if the second part of the for loop is empty, then the loop will be executed indefinitely.

Task: Raise a number to the power of a number using a for loop.

Solution:

varnum=2;
varpower=10;
varresult=1;
for(var subpower=1;subpower<=power;subpower++)
{

document.write((result=result*num) + “<br \/>”);

};

Result:

2
4
8
16
32
64
128
256
512
1024


This entry was posted in Javascript (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.