Changing an external variable using a js loop. For Loops in JavaScript

That indentation can be considered an indicator of code complexity (albeit a rather rough one). Indentations themselves are neutral, since they are just a means of formatting text, but the whole point is that they are used to highlight special blocks of programs, for example, control structures. When reading code and encountering an indentation, the programmer is forced to take into account what the indentation indicates, to keep in mind the context in which the selected block exists. This, naturally, is repeated if another special fragment appears in the indented section of code.

If you do not pay attention to the content of the texts, then this is what complex code usually looks like, sections of which look like the letters “V” lying on its side, and simple code, a block of which, if you do not take into account the different lengths of the lines, looks like a rectangle.


The more indentations, the more complex the code usually is.

Constructs that need to be indented will always be in the code; there is no talk of getting rid of them completely. However, we have the power to reduce the complexity of the programs we write by rationally choosing abstractions to solve the problems we face.

Let's take arrays for example. Traditionally, various types of cycles are used to process them. The concepts of “array” and “loop” are inextricably linked in the minds of many programmers. However, the cycle is a very ambiguous construction. Here's what Louis Atentzio writes about loops in his book Functional Programming in JavaScript: “A loop is a rigid control construct that is not easy to reuse and difficult to integrate with other operations. Also, using loops means creating code that changes with each iteration."


Is it possible to get rid of cycles?

The cycle is one of the main structural control structures, and, in fact, we are not going to say that cycles are an evil that needs to be gotten rid of. Our main goal is to reduce the complexity of our own code by minimizing the use of loops when processing arrays. Is it possible? We invite you to find out together.

Cycles

We've already talked about how control constructs like loops add complexity to your code. But why is this so? Let's take a look at how loops work in JavaScript.

There are several ways to organize loops in JS. In particular, one of the basic types of loops is while . Before we delve into the details, let's prepare a little. Namely, we will create a function and an array with which we will work.

// oodlify:: String -> String function oodlify(s) ( return s.replace(//g, "oodle"); ) const input = [ "John", "Paul", "George", "Ringo", ];
So, we have an array, each element of which we are going to process using the oodlify function. If you use a while loop to solve this problem, you will get the following:

Let i = 0; const len ​​= input.length; let output = ; while (i< len) { let item = input[i]; let newItem = oodlify(item); output.push(newItem); i = i + 1; }
Note that we use the i counter to keep track of the currently processed array element. It must be initialized to zero and incremented by one in each iteration of the loop. In addition, you need to compare it with the length of the array, with len, in order to know when to stop working.

This pattern is so common that JavaScript has an easier way to do this: a for loop. Such a loop will solve the same problem as follows:

Const len ​​= input.length; let output = ; for (let i = 0; i< len; i = i + 1) { let item = input[i]; let newItem = oodlify(item); output.push(newItem); }
The for loop is a useful construct because it puts all the standard auxiliary counter operations into top part block. Using while , it is easy to forget about the need to increment counter i , which will lead to an infinite loop. The for loop is definitely much more convenient than the while loop. But let's slow down and take a look at what our code is trying to achieve. We want to process, using the oodlify() function, each element of the array and put the result into a new array. The counter itself, used to access array elements, is not of interest to us.

This pattern of working with arrays, which involves performing certain actions on each element, is very common. As a result, ES2015 introduced a new loop design that allows you to forget about the counter. This is a for…of loop. Each iteration of this loop provides the next element of the array. It looks like this:

Let output = ; for (let item of input) ( let newItem = oodlify(item); output.push(newItem); )
The code looks much cleaner. Please note that there is no counter or comparison operation. With this approach, you don't even need to access a specific array element by index. The for…of loop takes care of all the auxiliary operations.

If we complete our study of ways to work with arrays and use for…of loops everywhere instead of for loops, this will already be a good step forward by simplifying the code. But...we can go further.

Transformation of arrays

The for…of loop looks much cleaner than the for loop, but it also has a lot of auxiliary elements in the code. So, you need to initialize the output array and call the push() method in each iteration of the loop. The code can be made even more compact and expressive, but before we do that, let's expand the demo problem a little. What if you need to process two arrays using the oodlify() function?

Const fellowship = [ "frodo", "sam", "gandalf", "aragorn", "boromir", "legolas", "gimli", ]; const band = [ "John", "Paul", "George", "Ringo", ];
A completely obvious solution is to use two loops and process the arrays in them:

Let bandoodle = ; for (let item of band) ( let newItem = oodlify(item); bandoodle.push(newItem); ) let floodleship = ; for (let item of fellowship) ( let newItem = oodlify(item); floodleship.push(newItem); )
Quite a working option. And code that works is much better than code that does not solve the problem assigned to it. But two very similar pieces of code don't fit particularly well with the DRY software design principle. The code can be refactored to reduce repetition.

Following this idea, we create the following function:

Function oodlifyArray(input) ( let output = ; for (let item of input) ( let newItem = oodlify(item); output.push(newItem); ) return output; ) let bandoodle = oodlifyArray(band); let floodleship = oodlifyArray(fellowship);
This looks much better, but what if there is another function with which we also want to process array elements?

Function izzlify(s) ( return s.replace(/+/g, "izzle"); )
Now the oodlifyArray() function will not help. However, if we create another similar function, this time izzlufyArray() , we will repeat ourselves again. Still, let's create such a function and compare it with oodlifyArray() :

Function oodlifyArray(input) ( let output = ; for (let item of input) ( let newItem = oodlify(item); output.push(newItem); ) return output; ) function izzlifyArray(input) ( let output = ; for ( let item of input) ( let newItem = izzlify(item); output.push(newItem); ) return output; )
The two functions are incredibly similar. Maybe we can summarize the pattern they follow? Our goal is this: “We have an array and a function. We need to get a new array into which the results of processing each element of the original array using the function will be written.” This method of processing arrays is called “mapping” or “transformation” (mapping in English terminology). Functions that perform such operations are usually called "map". This is what our version of such a function looks like:

Function map(f, a) ( let output = ; for (let item of a) ( output.push(f(item)); ) return output; )
Although the loop is now a separate function, it was not possible to completely get rid of it. If you go all the way and try to do without cyclic constructs entirely, you can write a recursive version of the same thing:

Function map(f, a) ( if (a.length === 0) ( return ; ) return .concat(map(f, a.slice(1))); )
The recursive solution looks very elegant. Just a couple of lines of code and a minimum of indentation. But recursive implementations of algorithms are usually used with great caution, and they also suffer from poor performance in older browsers. And, in fact, we don't really need to write a function to implement the mapping operation ourselves, unless there is a good reason for doing so. What our map function does is such a common task that JavaScript has a built-in map() method. If you use this method, the code will look like this:

Let bandoodle = band.map(oodlify); let floodleship = fellowship.map(oodlify); let bandizzle = band.map(izzlify); let fellowship = fellowship.map(izzlify);
Notice that there is no indentation or looping at all. Of course, when processing data, somewhere in the depths of JavaScript, loops can be used, but this is no longer our concern. Now the code is both concise and expressive. Moreover, it is simpler.

Why is this code simpler? This may seem like a stupid question, but think about it. Is it simpler because it's shorter? No. Compact code is not a sign of simplicity. It is simpler because with this approach we have broken the problem into parts. Namely, there are two functions that work with strings: oodlify and izzlify. These functions don't need to know anything about arrays or loops. There is another function - map, which works with arrays. At the same time, it is completely indifferent to what type of data is in the array, or what exactly we want to do with this data. It simply executes any function passed to it, passing it the elements of the array. Instead of mixing everything up, we separated string processing and array processing. That is why the final code turned out to be simpler.

Array convolution

So, the map function is very useful, but it does not cover all array processing options that use loops. It is good in cases where, based on a certain array, you need to create a new one with the same length. But what if we need, for example, to add up all the elements of a numeric array? Or what if you need to find the shortest string in the list? Sometimes you need to process an array and, in fact, generate a single value based on it.

Let's look at an example. Let's say we have a list of objects, each of which represents a superhero:

Const heroes = [ (name: "Hulk", strength: 90000), (name: "Spider-Man", strength: 25000), (name: "Hawk Eye", strength: 136), (name: "Thor", strength: 100000), (name: "Black Widow", strength: 136), (name: "Vision", strength: 5000), (name: "Scarlet Witch", strength: 60), (name: "Mystique", strength: 120), (name: "Namora", strength: 75000), ];
We need to find the strongest hero. In order to do this, you can use the for…of loop:

Let strongest = (strength: 0); for (let hero of heroes) ( if (hero.strength > strongest.strength) ( strongest = hero; ) )
All things considered, this code isn't that bad. We loop through the array, storing the object of the strongest hero we looked at in the strongest variable. In order to see the pattern of working with an array more clearly, let’s imagine that we also need to find out the total strength of all the heroes.

Let combinedStrength = 0; for (let hero of heroes) ( combinedStrength += hero.strength; )
In each of these two examples there is a work variable that is initialized before the loop starts. Then, in each iteration, one element of the array is processed and the variable is updated. In order to highlight the work scheme even better, we will move the operations performed inside the loops into functions, and rename the variables in order to emphasize the similarity of the actions performed.

Function greaterStrength(champion, contender) ( return (contender.strength > champion.strength) ? contender: champion; ) function addStrength(tally, hero) ( return tally + hero.strength; ) const initialStrongest = (strength: 0); let working = initialStrongest; for (hero of heroes) ( working = greaterStrength(working, hero); ) const strongest = working; const initialCombinedStrength = 0; working = initialCombinedStrength; for (hero of heroes) ( working = addStrength(working, hero); ) const combinedStrength = working;
If everything is rewritten as shown above, the two loops end up being very similar. The only thing that distinguishes them is the functions called in them and the initial values ​​of the variables. In both loops the array is collapsed to a single value. In English terminology, such an operation is called “reducing”. Therefore, we will create a reduce function that implements the discovered pattern.

Function reduce(f, initialVal, a) ( let working = initialVal; for (let item of a) ( working = f(working, item); ) return working; )
It should be noted that, as with the map function pattern, the reduce function pattern is so widespread that JavaScript provides it as a built-in array method. Therefore, unless there is a special reason for it, there is no need to write your own method. Using the standard method the code would look like this:

Const strongestHero = heroes.reduce(greaterStrength, (strength: 0)); const combinedStrength = heroes.reduce(addStrength, 0);
If you take a closer look at the final result, you will find that the resulting code is not much shorter than what was before, the savings are very small. If we had used the reduce function, written ourselves, then, in general, the code would have been larger. However, our goal is not to write short code, but to reduce its complexity. So, have we reduced the complexity of the program? I can say that they have reduced it. We have separated the looping code from the code that processes array elements. As a result, individual sections of the program became more independent. The code turned out simpler.

At first glance, the reduce function may seem quite primitive. Most examples of this function demonstrate simple things like adding all the elements of numeric arrays. However, nowhere does it say that the value that reduce returns must be a primitive type. It could be an object or even another array. When I first realized this, it amazed me. You can, for example, write an implementation of an array mapping or filtering operation using reduce . I suggest you try it yourself.

Filtering Arrays

So, there is a map function to perform operations on each element of the array. There is a reduce function that allows you to compress an array to a single value. But what if you only need to extract some of the elements from the array? In order to explore this idea, let's expand the list of superheroes and add some additional data there:

Const heroes = [ (name: "Hulk", strength: 90000, sex: "m"), (name: "Spider-Man", strength: 25000, sex: "m"), (name: "Hawk Eye", strength: 136, sex: "m"), (name: "Thor", strength: 100000, sex: "m"), (name: "Black Widow", strength: 136, sex: "f"), (name : "Vision", strength: 5000, sex: "m"), (name: "Scarlet Witch", strength: 60, sex: "f"), (name: "Mystique", strength: 120, sex: "f "), (name: "Namora", strength: 75000, sex: "f"), ]);
Now suppose there are two problems:

  1. Find all female heroes.
  2. Find all heroes whose power exceeds 500.
It is quite possible to approach the solution of these problems using the good old for…of loop:

Let femaleHeroes = ; for (let hero of heroes) ( if (hero.sex === "f") ( femaleHeroes.push(hero); ) ) let superhumans = ; for (let hero of heroes) ( if (hero.strength >= 500) ( superhumans.push(hero); ) )
In general, it looks quite decent. But here a repeating pattern is visible to the naked eye. In fact, the loops are exactly the same, they differ only in the if blocks. What if we put these blocks into functions?

Function isFemaleHero(hero) ( return (hero.sex === "f"); ) function isSuperhuman(hero) ( return (hero.strength >= 500); ) let femaleHeroes = ; for (let hero of heroes) ( if (isFemaleHero(hero)) ( femaleHeroes.push(hero); ) ) let superhumans = ; for (let hero of heroes) ( if (isSuperhuman(hero)) ( superhumans.push(hero); ) )
Functions that return only true or false are sometimes called predicates. We use a predicate to decide whether to store the next value from the heroes array in a new array.

The way we rewrote the code made it longer. But, after highlighting the predicate functions, the repeating sections of the program became better visible. Let's create a function that will allow us to get rid of these repetitions:

Function filter(predicate, arr) ( let working = ; for (let item of arr) ( if (predicate(item)) ( working = working.concat(item); ) ) return working; ) const femaleHeroes = filter(isFemaleHero, heroes); const superhumans = filter(isSuperhuman, heroes);
Here, as with the built-in map and reduce functions, JavaScript has the same thing that we wrote here in the form of a standard filter method on the Array object. Therefore, there is no need to write your own function unless clearly necessary. Using standard means the code will look like this:

Const femaleHeroes = heroes.filter(isFemaleHero); const superhumans = heroes.filter(isSuperhuman);
Why is this approach so much better than using for loop...of ? Think about how you can use this in practice. We have a task like: “Find all the heroes who...”. Once you figure out that you can solve the problem using the standard filter function, the job becomes easier. All we need to do is tell this function which elements we are interested in. This is done by writing one compact function. There is no need to worry about processing arrays or additional variables. Instead, we write a tiny predicate function and the problem is solved.

And, as with other functions that operate on arrays, using filter allows you to express more information in less code. No need to read the whole thing standard code loop in order to understand what exactly we are filtering. Instead, everything you need to understand is described right when the method is called.

Search in arrays

Filtration is a very useful operation. But what if you only need to find one superhero from the list? Let's say we are interested in Black Widow. The filter function can be used to solve this problem:

Function isBlackWidow(hero) ( return (hero.name === "Black Widow"); ) const blackWidow = heroes.filter(isBlackWidow);
The main problem here is that such a solution is not effective. The filter method goes through each element of the array. However, it is known that in the array only one hero is called Black Widow, which means that you can stop after this hero is found. At the same time, predicate functions are convenient to use. Therefore, let's write a find function that will find and return the first matching element:

Function find(predicate, arr) ( for (let item of arr) ( if (predicate(item)) ( return item; ) ) ) const blackWidow = find(isBlackWidow, heroes);
Here, again, it must be said that JavaScript has a built-in function that does exactly what is needed:

Const blackWidow = heroes.find(isBlackWidow);
As a result, as before, we were able to express our idea more concisely. Using the built-in find function, the task of searching for a specific element comes down to one question: “By what criteria can we determine that the desired element has been found?” You don't have to worry about the details.

About the reduce and filter functions

Readers have noticed that it is inefficient to iterate through the list of heroes twice in the examples above for the reduce and filter functions. Using the spread operator from ES2015 allows you to conveniently combine two array folding functions into one. Here's a modified piece of code that allows you to iterate through the array only once:

Function processStrength((strongestHero, combinedStrength), hero) ( return ( strongerHero: greaterStrength(strongestHero, hero), combinedStrength: addStrength(combinedStrength, hero), ); ) const (strongestHero, combinedStrength) = heroes.reduce(processStrength, (strongestHero : (strength: 0), combinedStrength: 0));
I can't help but notice that this version will be a little more complicated than the one in which the array was traversed twice, but if the array is huge, reducing the number of passes over it can be very useful. In any case, the order of complexity of the algorithm remains O(n).

Results

I think the features presented here are a great example of why thoughtfully chosen abstractions are both useful and look good in code. Let's say that we use built-in functions wherever possible. In each case the following results:
  1. We get rid of loops, which makes the code more concise and, most likely, easier to read.
  2. The template used is described using a suitable standard method name. That is, map, reduce, filter, or find.
  3. The scale of the task is reduced. Instead of writing code to process the array yourself, you just need to tell the standard function what to do with the array.
Note that in each case compact pure functions are used to solve the problem.

In fact, if you think about all this, you can come to a conclusion that, at first, seems surprising. It turns out that if you use only the four array processing patterns described above, you can remove almost all loops from your JS code. After all, what is done in almost every loop written in JavaScript? It either processes or constructs a certain array, or does both. In addition, JS has other standard functions for working with arrays, you can easily learn them yourself. Getting rid of loops almost always reduces the complexity of programs and writes code that is easier to read and maintain.

Dear JavaScript developers, do you have any standard functions in mind that can improve the code by getting rid of some common “homemade” constructs?

Tags: Add tags

The for loop is the most commonly used loop in JavaScript.

Its design looks like this:

For (start; condition; step) ( /* loop body */ )

It's really simple. Let's look at an example:

Var i; for (i = 1; i

In this example:

  • Start of the cycle: i = 1 (starting from value i = 1)
  • Cycle condition: i
  • Cycle step: i++ (at each loop step i is increased by 1)
  • Loop body: document.write("

    The cycle step number is executed: " + "

    "); (display a message on the screen)

Step-by-step algorithm for executing this for loop, in more detail:

  1. Start of the loop: variable i is set to 1. This part of the loop is executed once.
  2. The loop condition (i 5) is checked - the end of the loop.
  3. The body of the loop is executed.
  4. The loop step is executed. In our case i++. It is always executed after the body of the loop.
  5. Return to point 2.

If the body of the loop consists of one instruction, then the curly braces {...} it is not necessary to put it.

The variable i does not disappear after the loop ends. It continues to exist and its value after the end of the cycle will be equal to 6.

Let's summarize this data in a new example:

Var i; for (i = 1; i

Here, curly braces were not used to create the loop body.

Braces {...} form a block in JavaScript - this is one of the language constructs. That is, if there are curly braces after the for loop statement, this means that the JavaScript handler must execute the entire JavaScript block.

Similar to a block, you can specify a function in a for loop. Here's an example:

For (var i = 1; i

But when declaring a function, there are curly braces {...} required. Their absence will result in an error.

Please note that in this loop the variable i is declared at the beginning of the loop: for ( var i = 1; i

Skipping for parts

In general, the beginning of the cycle need not be written:

Var i = 1; for(;i

You see, at the beginning of the loop there is just a semicolon, and the loop works fine.

You can also remove the step:

Var i = 1; for(;i

This for loop has turned into an analogue of the while loop (i

You can put an expression in a condition that changes a variable.

For (i = 10; i--;) ( document.write("

The loop step is executed: " + i + ".

"); }

Because the JavaScript interpreter expects to receive a boolean value, any value results in boolean type, then when, as a result of the next decrement, the variable i becomes equal to 0 (false), the loop will stop.

Infinite for loop

Yes, yes, I know that it’s correct to write infinite :)

So, the loop will be endless if the condition is always true. Here's an example:

For (var i = 1; i

In this example, the variable i will decrease and never become greater than five. The loop will run forever. Try running this script. For me, Chrome “got lost in thought” and didn’t display anything on the screen, but continued to think and think.

Be careful to avoid accidentally creating endless loops.

Interrupting the for loop

To break a for loop, just like to break any other loop, use the break command. When the JavaScript engine encounters a break command in the body of a loop, it stops executing the loop and begins executing the script instructions that follow the loop. if there are any.

In the following example, we will stop the loop at the third iteration (third step).

For (var i = 1; i

Let's complicate the example a little

Let's perform only 100 iterations of the infinite loop.

Var $counter = 1; for (var i = 1; i

Next iteration: continue

The continue command ends the current iteration and begins the next one.

The continue directive is the “younger sister” of the break directive; it stops only the iteration, and not the entire loop.

For (var i = 1; i

The loop below uses continue to output odd values:

For (var i = 0; i

Of course, odd values ​​can be output using a loop like this without a continue directive:

For (var i = 0; i

The break / continue directives in the "?"

Let's briefly describe the question mark operator "?". It is similar to an if construct.

Logical design:

If (condition) ( a(); ) else ( b(); )

Works the same as code with the "?" operator.

Condition? a() : b(); var i = 2; document.write("

Part 1.

"); if (i == 2) document.write("

The condition worked.

"); else document.write("

The condition didn't work.

"); document.write("

Part 2.

"); i == 2 ? document.write("

The condition worked.

") : document.write("

The condition didn't work.

");

So, important, you cannot use break/continue to the right of the "?" operator

In JavaScript, syntactic constructs that do not return values ​​are prohibited from being used in the "?" operator.

The below example is not working, it contains an error:

For (var i = 0; i

Labels for break / continue

Sometimes it becomes necessary to create nested loops. In such a case, while the nested loop is running, it may be necessary to stop the parent loop or stop iteration of the parent loop. Tags are used for this.

You can use labels to designate loops, then use break or continue to exit the loop or continue the loop with a new iteration.

Markers are the only way for the break and continue commands to affect the execution of the outer loop.

The label instruction is used only in conjunction with break or continue to provide an alternative exit from a loop.

The label has the syntax "name:", the label name must be unique. The mark is placed before the cycle, in the same line or with a line break.

Similarly, you can use the break directive in this place. But if you use it, as you understand, the execution of cycles will stop.

Var i, j; metka1: for (i = 0; i

JavaScript does not have a goto statement like PHP; it is only possible to use break or continue labels.

Tags are rarely used in JavaScript programming because they are thought to make the code harder to read and understand. It is recommended to use functions when coding.

Cycles are used to execute a certain section of code several times in a row.

Why is this necessary?- imagine that you need to square 100 array elements. If you access each element separately by its key, it will take 100 lines of code, and in order to write this code, you will need to spend quite a lot of time.

But this is not necessary - we have the opportunity to have JavaScript perform some operation for us the required number of times. For example, I squared all the elements of an array.

This is done using cycles.

while loop

Cycle while will be executed until right(true) the expression passed to it by the parameter. See syntax:

While (while the expression is true) (we execute this code cyclically; at the beginning of each loop we check the expression in parentheses) /* The loop will end when the expression is no longer true. If it was false initially, then it will never be executed! */

Basically a cycle while can be performed endlessly(but this will cause the script to hang!), just pass it an expression that will never become false. For example, like this:

Let's sequentially print the numbers from one to five using a while loop:

Var i = 0; //loop counter while (i< 5) { /* С помощью оператора ++ увеличиваем i на единицу при каждом проходе цикла. */ i++; alert(i); }

Notice the variable i- she is the so-called cycle counter. Counters are used to count how many times a loop has been executed. In addition, they serve an auxiliary role - in our task, we used a counter to display the numbers from 1 to 5.

It is customary to use letters for counters i, j And k.

for loop

Cycle for is alternative to while. It is more difficult to understand, but is often loved more than while because it takes up fewer lines.

For (initial commands; condition for ending the loop; commands after the loop) (loop body)

Initial commands- this is what will be executed before the loop starts. They will only be executed once. Usually the initial values ​​of the counters are placed there, for example: i = 0.

Loop end condition - as long as it's true, the loop will work, example: i.

Commands after the loop- these are commands that will be executed every time the loop is completed. Usually the counters are increased there, for example: i++.

Let's use a loop for Let's print numbers from 0 to 9 sequentially:

/* At the beginning of the loop, i will be equal to zero, the loop will be executed until i< 10, после каждого прохода к i прибавляется единица: */ for (var i = 0; i < 10; i++) { alert(i); //выведет 0, 1, 2... 9 }

Cycle without body

You can omit curly braces in loops - in this case, the loop will execute only one line below it (I don’t recommend doing this, it often leads to errors):

For (var i = 0; i< 10; i++) //<--- точки с запятой нет alert(i); //выведет 0, 1, 2... 9

But if after ) put a semicolon - the loop will close and the next line will not go into it, you will get a so-called loop without a body, which in our case will simply scroll and as a result change the value of the variable i:

For (var i = 0; i< 10; i++); //<--- точка с запятой есть alert(i); //выведет 9

This loop is sometimes used; you will see examples of its use when analyzing problems into loops.

Multiple commands in a for loop

If we need to execute several commands in parentheses, we indicate them separated by commas:

For (var i = 0, j = 2; i

Let's look at the above loop: before the loop passes, two commands will be executed: var i = 0, j = 2(note that var is written here once), and after each iteration - three times: i++, j++, i = i + j.

This example is not particularly useful from a programming point of view; it simply shows schematically that this can be done. Remember it, it will be useful to you in the future.

for loop for arrays

Using a loop for You can iterate through the elements of an array sequentially. This is done as follows:

<= arr.length-1; i++) { alert(arr[i]); //выведет 1, 2, 3, 4, 5 }

The key point is that we iterate from zero to the length of the array minus 1 (since the number of the last element of the array is one less than its length).

You don’t have to take away a unit, but a place <= do < :

Var arr = ; for (var i = 0; i< arr.length; i++) { alert(arr[i]); //выведет 1, 2, 3, 4, 5 }

for-in loop

To iterate through an object, a so-called loop is used. for-in. Let's see how it works.

Let us be given the following object:

Var obj = (Kolya: 200, Vasya: 300, Petya: 400);

Let's get his keys out. To do this we use the following construction: for (key in obj), Where obj is the object we are iterating over, and key- this is a variable into which the keys of the object will be stored sequentially (its name can be anything you can think of - that’s what it will be).

That is, in this loop there is no need to specify an ending condition - it will iterate over the object’s keys until they end.

So, this is how we will print out all the keys of the object (one by one):

Var obj = (Kolya: 200, Vasya: 300, Petya: 400); for (key in obj) ( alert(key); //will display "Kolya", "Vasya", "Petya" )

If we need values ​​rather than keys, we need to access our object by key, like this: obj.

How it works: in a variable key first there will be "Kolya", that is obj in this case it doesn't matter obj["Kolya"], the next time the loop passes through the variable key will be "Vasya" and so on.

So, let's display all the elements of the object:

Var obj = (Kolya: 200, Vasya: 300, Petya: 400); for (key in obj) ( alert(obj); //will display 200, 300, 400 )

break instruction

Sometimes we need to terminate the loop early; in the case of a for loop, this means before the loop has iterated through all the elements of the array.

Why might this be needed? For example, we are faced with the task of displaying array elements until the number 3 is encountered. As soon as it is encountered, the loop must complete its work.

This can be done using the instructions break- if the execution of the loop reaches it, the loop will end its work.

Let's solve the above problem - break the loop as soon as we encounter the number 3:

Var arr = ; for (var i = 0; i< arr.length; i++) { if (arr[i] === 3) { break; //выходим из цикла } else { alert(arr[i]); } }

Continue instruction

There is also an instruction continue, upon reaching which the loop begins a new iteration. Sometimes it can be useful for simplifying code, although almost always the problem can be solved without it.

What should you do next:

Start solving problems using the following link: problems for the lesson.

When you decide everything, move on to studying a new topic.

Very often you need a certain part of a program to be executed many times. Of course, you can simply do this: copy and paste the required number of times. However, this is absurd, especially if the action must be performed, for example, 1000 times. That's why there are so-called cycles, which is present in most programming languages. And I will tell you about them.

Contains a specific code that is scrolled multiple times. There are several types of cycles: for, while And do-while.

Let's start with the very first cycle (and the most popular) - for loop. The general appearance of this cycle is as follows:

For (iteration_variable = initial_value; condition; action_after_each_iteration) (
//program code
}

Let me comment on what is written here. First comes - iteration variable. This is the normal variable name for iteration. Next comes initial_value. Actually, the name speaks for itself. Next comes a condition, when fulfilled (that is, it returns true) the loop is run one more time, and finally an action that is executed after each iteration. Typically this is a change to a variable for the iteration.

Let's write a simple script that will display the number of loop iterations:

For (i = 0; i< 100; i++)
document.write(i + " ");

Here we have set a variable for iteration (called i), which was assigned the value 0 . Next the condition is checked: i< 100 . If it is executed, then one iteration of the loop is executed. After each iteration is completed, i++(that is, increasing the variable i on 1 ). The condition is checked again, and if it is true, then another iteration is performed. And so on until the condition i< 100 will not become false. Obviously, it will be false only after 100 iterations. Thus, this loop will be executed 100 times, which we can see if we run this script. And one more thing. Since we only have one operator executed here ( document.write()), then the presence of curly braces is optional. If you have 2 or more operators running in a loop, then you need to install them.

Now let's talk about the second type loops in JavaScript - while. Basically, the cycle is very similar to for(although all cycles are similar). But here the general view is different:

While (condition) (
//program code
}

As you can see, there is no variable for iteration, nor any actions after iteration. The conclusion follows from this: in order to exit the loop, it is necessary to do so in the loop itself so that " condition" has become false. If this is not done, a loop will occur, and, consequently, your script will hang.

Let's implement the same task as before, but using while loop.

Var i = 0;
while (i< 100) {
i++;
document.write(i + " ");
}

Before starting the loop we created a variable i, which was assigned an initial value. Then, before starting the loop, the condition is checked, and if it is true, then an iteration of the loop is launched, in which we increment the variable for iteration (otherwise a loop will occur). And we display this variable.

And finally the last view loops in JavaScript - do-while loop. The syntax is:

Do(
//program code
) while (condition)

Very similar to a cycle while, however, there is only one, but very fundamental difference. If while loop First it checks the condition, and then it executes the iteration or not. That do-while loop first it performs the iteration, and only then checks the condition. And if it is false, it exits the loop. In other words, regardless of the condition, this loop is guaranteed to be executed at least once. I think that this code will be redundant, but still.

Var i = 0;
do(
i++;
document.write(i + " ");
) while (i< 100)

I won’t explain the code, I’m sure you’ll figure it out without me. So I'd better move on to two interesting operators: break And continue.

Let's start with break. This operator allows you to jump out of the loop early. Let's write the following code:

For (i = 0; i< 100; i++) {
if (i == 50) break;
document.write(i + " ");
}

You can run this script and find that only numbers up to 49 , since when i = 50 the loop was interrupted, thanks to the operator break.

Now I'm talking about the operator continue. This operator allows you to move to the next iteration of the loop. In order not to describe too much here, it’s better to show an example right away:

For (i = 0; i< 100; i++) {
if (i == 50) continue;
document.write(i + " ");
}

If you run this script, you will see that the number is missing 50 . This happened because when i = 50, we move on to the next iteration of the loop, before which i increases by 1 and becomes equal 51st.

That, it seems, is all I wanted to write about JavaScript loops. I hope everything has become clear to you. You can also come up with a problem for yourself and solve it. This will be a great workout.

Loops are designed to execute the same instructions over and over again.

There are 4 types of loops in JavaScript:

  • The for loop. This loop is used when the exact number of repetitions of the same instructions is known.
  • While loop. It is designed to execute the same instructions as long as a given condition is true.
  • The do...while loop. This loop is similar to the while loop, but the condition is checked not before executing repeated instructions, but after them. This way, unlike a while loop, even if the condition is initially false, the statements will be executed at least once.
  • The for...in loop. It is used when you need to iterate through all the properties in an object or each element in an array.

for loop

For loop syntax:

For (initialization; condition; final expression) ( /* loop body */ )

  • initialization is an expression that is executed once before the loop is executed; usually used to initialize a counter;
  • a condition is an expression whose truth is checked before each iteration; if the expression evaluates to true, then iteration is performed, otherwise the for loop exits;
  • final expression is an expression that is executed at the end of each iteration; usually used to change the counter;
  • loop body - instructions that need to be repeated.

Let's look at an example of a loop that will print numbers from 1 to 9 to the console:

Var i; // Loop for from 1 to 9, in steps of 1 for (i = 1; i<= 9; i++) { console.log(i); }

In this example:

  • initialization: i = 1 (assigning variable i the value 1);
  • loop termination condition: i<= 9 (значение переменной i не меньше 9);
  • expression to be executed at the end of each iteration: i++ (increase the value of variable i by 1);
  • instructions to follow: console.log(i) (printing the counter value to the console).

Optional parts of a for loop

In for, the initialization block is optional.

Var i = 1; // Loop for for (; i<= 9; i++) { console.log(i); }

The condition block in a for loop is also optional. Without a condition, the loop will be executed an infinite number of times. In this case, to interrupt it (exit the loop), you must use the break statement.

Var i; // Loop for for (i = 1; ; i++) ( if (i > 9) ( // condition for interrupting the loop break; ) console.log(i); )

The final for expression is also optional. In this case, the loop counter can, for example, be changed in the body.

Var i; // For loop for (i = 1; i<= 9 ;) { console.log(i); i++; }

You can omit 3 expressions altogether:

Var i = 1; // Loop for for (; ;) ( if (i > 9) ( break; ) console.log(i); i++; )

You can use an empty expression (;) as the body of a for loop.

For example:

Var arrA = , arrB = ; for (i = 0; i< arrA.length; arrB[i] = arrA / 2) ; console.log(arrB); //

Examples of using for

Using a for loop to iterate through array elements:

Var arr = , // array i = 0, // counter lenArr = arr.length; // array length for (i; i< lenArr; i++) { console.log(arr[i]); }

Break and continue instructions

In addition, special instructions break and continue can be used inside the body of loops.

The break statement is intended to terminate the execution of a loop. Those. it exits the current loop and transfers control to the instruction following it.

The continue statement interrupts the current iteration of the loop and moves on to the next one.

An example in which we will output odd numbers from 1 to 11 to the console:

Var i; for (i = 1; i <= 11; i++) ( // if the number in variable i is even, then move on to the next iteration if (i %2 === 0) ( continue; ) // print the value of variable i to the console console.log(i); ) // 1, 3, 5, 7, 9, 11

Loop with precondition while

The while loop executes the same statements (loop body) until some condition is true. The truth of the condition is checked before each execution of the loop body. If the condition is false before the first iteration, then the loop is never executed.

// declaring variable a and assigning it the value 0 var a=0; //while loop with condition a

Loop with do...while postcondition

The do...while loop, like the while loop, executes the same statements (the body of the loop) until some condition is true. But unlike the while loop, in the do...while loop the condition is checked after each execution of the loop body. Even if the condition is initially false, the body of the loop will still be executed once (since the condition is checked after the body of the loop is executed).

// declaring variable a and assigning it the value 0 var a=0; //do...while loop with condition a

As noted above, the for...in loop is used to iterate through array elements and object properties. In this lesson we will only look at the general syntax of the for...in loop, but we will get to know it in more detail in the following lessons.

The way the for...in loop works is that the variable x takes all the property names of the object y or the indices of the array y . Thus, in each iteration, an object property or array element is available to you.