I can’t learn syntax for

Asked

Viewed 481 times

4

I can learn subjectively for a few seconds, but I can’t fix it no matter how hard I try. I’ve already repeated classes, I’ve done exercises and everything, but the syntax and its variations just don’t fix it for me.

For example, if I do:

for(var i=0; i<10; i++){ 
    alert(i); 
}

Calling the alert within the loop, alert 9 windows at a time adding 1 number up to 10, normal. But do not understand why to call the alert(i) outside the loop appears only 10.

  • 3

    If you don’t understand why alert(i) outside the for displays "10", you are not understanding scope, not how it works a for. Show the entire code (Javascript only) you are using to better explain.

  • 1

    Related: http://answall.com/q/1237/129

8 answers

19

Syntax of the for:

for(
   INICIALIZACAO;
   CONDICAO para executar o CODIGO entre { };
   tarefa para fazer depois de cada execucao do CODIGO
)
{
   CODIGO a ser executado repetidas vezes, enquanto a CONDICAO for verdadeira
}

I will show you a description step by step. For this, I numbered the lines and decreased to 3 loops only:

1. for( var i=0; i<3; i++ )
2. {
3.    alert(i);
4. }
5. alert(i);

Okay, see how this code is understood by your system:

a) Estamos na linha 1. Aqui foi "criado" um for, e definido que i é zero;  
b) o programa avança para a linha 2, com i valendo zero;
c) avançamos para a linha 3 e é exibido o valor de i, que é zero;  
d) o programa avança para a linha 4. Como o escopo do for encerrou, é executado i++ e testado se i<3
e) i agora é um, portanto SIM, i é menor que três, então VOLTAMOS para a linha 2
f) avançamos para a linha 3, e é exibido o valor de i, que é um;
g) o programa avança para a linha 4. Como o escopo do for encerrou, é executado i++ e testado se i<3
h) i agora é dois, portanto SIM, i é menor que três, então VOLTAMOS para a linha 2
i) avançamos para a linha 3, e é exibido o valor de i, que é dois;
j) o programa avança para a linha 4. Como o escopo do for encerrou, é executado i++ e testado se i<3
k) i é três, portanto NÃO É menor que três, portanto AVANÇAMOS para a linha 5.  
l) Pronto, acabou o loop, i vale 3
m) na linha 5, é exibido o valor de i, que é 3

Note that I oversimplified logic absurdly, the steps are a little more complex internally. As mentioned by @mgibsonbr, i<3 test already happens between steps (a) and (b), "jumping" face to line 5 if the result is not true (but don’t worry about it now).

The best is to understand that this "comes and goes" from line 2 to line 4 only happens while the condition ( i<3 ) is true.

The code above equals this one:

var i = 0; // iniciamos com i=0
for(;i<3;) // executamos repetidamente o que está entre "{" e "}" enquanto i<3
{
    alert(i); // mostramos i
    i++;      // incrementamos i
}
alert(i); // Somente quando i<3 for falso é que chegaremos nessa linha aqui
  • very enlightening. you really helped me a lot!

10

If you’re learning bonds for the first time, it helps to start with a simpler one - like the while - and only then pass to the for. This will help you understand exactly what happens in your code.

for ( var i = 0 ; i < 10 ; i++ ) { alert(i); }

Is equivalent to:

// Iniciação
var i = 0;
// Teste da condição
while ( i < 10 ) {
    // Corpo
    alert(i);
    // Passo
    i++;
}

Looking at it this way, you realize that:

  • The variable was created and assigned to zero even before the loop, and [in Javascript] it continues to exist after the loop ends;

        ...
    }
    alert(i); // A variável ainda existe aqui
    
  • There’s a chance he won’t get in the loop once!

    var i = 20;
    while ( i < 10 ) {
        ...
    
  • The step is executed before testing the condition; hence any side effect it has (in this case, the increment i) will occur no matter if the loop will continue or will stop:

        ...
        alert(i); // 9
        i++; // aumentou 1, pra 10
    } // Saiu do loop - pois a condição i < 10 ficou falsa
    alert(i); // 10
    

I suggest you try to master the while first, for all that other ties make the while can also do - in a simpler way, but not as concise. When you are well used to it, then you can start to see patterns in its use, and use the other ways to simplify these patterns:

  • A code is executed once before the loop, and is equal to what is in the body of the loop:

    código
    while ( condição ) {
        código
    }
    

    Can be simplified to:

    do {
        código
    } while(condição);
    
  • One code is executed before the loop, and another at the end of the repeating phase:

    início
    while ( condição ) {
        código
        fim
    }
    

    Can be simplified to:

    for ( início ; condição ; fim ) {
        código
    }
    

    The executed sequence is then as follows::

    • Zero iterations:

      início, condição
      
    • An iteration:

      início, condição, código, fim, condição
      
    • Two iterations:

      início, condição, código, fim, condição, código, fim, condição
      
    • Three iterations:

      início, condição, código, fim, condição, código, fim, condição, código, fim, condição
      
    • Etc..

  • perfect. it worked starting with while, now I’ve got it all in a clear + way.

9

The variable does not go out of scope (it is not "deleted") so the for ends, then the i gets the ultimate value from it.

The last comparison in your example is with i = 10. He does 10 < 10, which returns false, and exits the loop. Soon, it will print 10 out of the loop.

4

Well, first it is necessary to know when it will be for which server the FOR.

Basically, the FOR is for you to repeat an algorithm N times.

Syntax:

for(INICIO DAS VARIAVEIS; CONDIÇÃO ; CONSEQUENCIA ){
  //SEU CODIGO AQUI
}

Example:

var cont;
var totalVoltas = 10;
  for(cont = 0;cont < totalVoltas ;cont++){
    alert("Volta número "+cont);
  }

This code will go to you alert 10 times on the screen, the same way you asked the question. In this code, I INICIALIZEI A VARIÁVEL with the valor 0, right after I do the CONDIÇÃO, and in the end INCREMENTO plus 1 on the variable I initialized at the start of FOR.

The FOR is widely used to traverse Array, as it has access to all indexes by making this loop. Example:

var semanas = ["Domingo","Segunda","Terça","Quarta","Quinta","Sexta","Sábado"];
var cont;
var str = "Dias da Semana:\n";
//Como um array sempre começa na posição zero, o cont será zero.
for(cont = 0; cont < semanas.length;cont++){
  str += semanas[cont]+"\n";  //Aqui eu 'Acesso' o valor do array contido na posição referente ao valor de cont.
}
alert(str);

The why after the loop the value of i is 10 is that, the method of INCREMENTO changes the variable itself. So at the end of the loop, the cont was incrementado 10 times, coming to the end with 10.

All right, I hope I helped. :)

2

You have to understand to memorize !! It’s like a loop, a loop,

For i starting with 0 up to 10 adding ++ means step one on one,

Alert(1);

Return

For i starting with 1 up to 10 adding ++ means step one on one,

Alert(2);

Return

And so up to 10

for( var i=0; i<10; i++ )
{ 
 alert(i); 
}

2

Different structures of repetition: Enquanto(while), Para(for), Repita(do)

All three work for the same purpose, they run a line of code until the pre-set condition is reached.... o While and the Do does not have in its own basic structure a counter, so we must create one within it

Already the For has this structure by default, anyway... the three are practically the same thing, the only thing is that the for leaves the code to be executed more 'clean'

WHILE

Enquanto (condição) Faça
    (bloco de código)
Fim Enquanto

OF

Repita
    (bloco de código)
Ate (condição)

In both above there is the need to declare a counter, and increment it within the code block, otherwise the code is in loop infinity, and in most cases, especially in high-level languages, we do not want this to occur

FOR

Para (V) De (vi) Até (vf) Passo (p) Faça
    (bloco de código)
Fim Para

In this case there is no need to declare the counter and increment it within the code block, since we have already done this in the pre-set condition....

The three implementations serve the same purpose, going more of its ease to work with them.....

It would be something like the GOTO so acclaimed in some "archaic" languages In the same way we could create a simple structure of if using the goto

EXP:

linha de memoria 1: I = 0;
linha de memoria 2: Se (I<=5){
linha de memoria 3:    I += 1;
linha de memoria 4:    (bloco de código)
linha de memoria 5:    GOTO linha de memoria 2;
linha de memoria 6: Fim-Se

ANYWAY... it’s complicated to explain, we just have to add that it serves as a simpler code repeater to be written, so hj is so used, the counter vc already defines and increases in the condition itself

1

I believe your question is "why does it appear from 1 to 10 when I put inside the keys and when I put out appears only 10"

in your example the FOR ta by adding +1(such as i++) in the variable "i" each time it rotates in the FOR, then basically the sum was done and then shown the value, different from when it is inside the FOR that every +1 that happens it already invokes the "Alert".

what happens inside the computer when you put Alert inside the for is:

i=0
Alert(0) //mostra mensagem
i=1 //0+1 = 1
alert(1)
i=2 //1+1 = 2
alert(2)
i=3 //2+1 = 3
alert(3)

and so on

In the case of Alert out of the is what happens on the computer is the following:

i=0
i=1 //0+1
i=2 //1+1
i=3 //2+1
i=4 //3+1
i=5 //4+1
i=6 //5+1

then basically what happens is that it sums everything up and then it shows(when ta outside of the FOR) and when it ta inside, every time it adds up to 1 it will run the Alert() also what will show the CURRENT number that is in the variable i...

I hope you understand the difference between using inside and outside

0

Well, the first step is to learn what is scope, which according to Maurício Samy Silva (the renowned Maujor), in Javascript:

A very important concept when declaring a variable is the so-called scope of the variable, which is the environment or, more precisely, the chunk or region of the script in which the variable assumes the value that was declared for it.

Variables of global scope, can be called anywhere in the script, whereas variables of local scope can be called only in the excerpt of the script in which they were declared. To declare a variable in the local scope the keyword is used var, already to declare a variable in the global scope, omit it:

var a = 5; // Variável "a" declarada no escopo local
b = 10; // Variável "b" declarada no escopo global

Example illustrating the operation of the scope

a = 5;

primeira_funcao = function(){

var a = 15;

alert(a); // alerta 15

}

primeira_funcao(); // Chamada à primeira função

segunda_funcao = function(){

alert(a); // alerta 5

}

segunda_funcao(); // Chamada à segunda função

alert(a); // alerta 5

As seen in the example above, the variable a initially declared with the value of 5, was alerted, both in the second function and called outside the functions, with its original value, only being changed the value of the same in the first function, where it was declared var a = 15; starting another variable with the name a, but in the local scope, just when called alert(a); was alerted 15 instead of 5.

The syntax of for is very well explained in the other answers, so I will not address it here, good studies ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.