I am a beginner with javaSCript and just wondering why the results are different when it's called "inside" the loop and "outside" the loop.
for (var i = 0; i < 5; i++) {
console.log(i);
// prints 0 1 2 3 4
}
console.log(i);
// prints 0 1 2 3 4 5
Because the for looping steps is :
1 - define a variable,
2 - check the condition,
3 - run the code inside the loop,
4 - and increase the loop variable value by 1 ,
But! After defining the variable and After the first loop, it will ignore the first argument var i = 0 and it will increment the loop variable by 1, and check the condition, why? Because in the for looping, the last thing to do is increase the loop variable by 1,
So the last loop will increase the loop variable by 1 and check the condition ,
Simply: the variable has changed through the loop to 5 because after the first loop it will increase the variable by 1 and checking the condition
I hope my answer will be useful to you!
That's how var in JS works and also that's how for loops in all languages work.
When you declare a variable using var keyword it is hoisted to the function scope, or global if not inside a function. This lets you access var outside of the for loop scope. Try changing var to let and see what happens.
Secondly, you don't see 5 printed in the for-loop because of your condition i < 5. i++ causes 'i' to go from 4 to 5 which breaks the for-loop conditions and the 'i' is not printed.
Lastly console.log(i) outside the for-loop should just print 5 because that is the value of i at that point and not
console.log(i);
// prints 0 1 2 3 4 5
// should print 5
Inside the loop it logs the numbers from 0 to 4. The last i++ sets i to 5, and the loop stops because i < 5 is no longer true. Then the console.log(i) after the loop logs this value.
During the loop execution, the condition i < 5 fails for "5<5" but still the value of i here becomes '5' which is executed outside of the loop
for (var i = 0; i < 5; i++) {
console.log("inside loop: " + i);
// prints 0 1 2 3 4
}
console.log("outside loop: " + i);
// prints just 5
Related
This question already has answers here:
Can a for loop increment/decrement by more than one?
(9 answers)
Closed 1 year ago.
I need to create loop number but with increment 0.5
for(var i = 1; i <= 10; i < i++){
var newOption = $('<option value="'+i+'">'+i+' Minute</option>');
$('.duration').append(newOption);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="duration"></select>
What I expected is like this:
1
1.5
2
2.5
3
3.5
So on until 10
Any idea how to do the trick?
Just use i+= 0.5 like this:
for(var i = 1; i <= 10; i+= 0.5){
var newOption = $('<option value="'+i+'">'+i+' Minute</option>');
$('.duration').append(newOption);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="duration"></select>
Just use i+= 0.5 in the last part of loop.
for(var i = 1; i <= 10; i+= 0.5) {
console.log(i)
}
A for loop has 3 parts:
for ([initialExpression]; [conditionExpression]; [incrementExpression])
statement
When a for loop executes, the following occurs:
The initializing expression initialExpression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.
The conditionExpression expression is evaluated. If the value of conditionExpression is true, the loop statements execute. If the value of condition is false, the for loop terminates. (If the condition expression is omitted entirely, the condition is assumed to be true.)
The statement executes. To execute multiple statements, use a block statement ({ ... }) to group those statements.
If present, the update expression incrementExpression is executed.
Control returns to Step 2.
So you can set any incrementExpression you want, like += 0.5 or anything else.
Loops and iteration
The operator is les then or equal. So why does it continue to loop one more time since when it looped 4 times, it reached one of it's conditions?
for (let i = 0; i <= 5; i++) {
console.log(i);
console.log("Hello World!");
}
You are correct that <= means less than or equal, but I believe you are confusing how loops work. The second statement in a for-loop declaration is called the condition, and defines when a loop can continue to execute. If the condition returns true, the loop body is executed. If false, it breaks.
If it helps, you can imagine it as a while loop where
for(declaration; condition; increment)
{
//loop body
}
is fundamentally equivalent to
declaration;
while(condition)
{
//loop body
increment;
}
A condition of i <= 5 means the loop will continue to execute as long as the i is less than or equal to 5. It does not mean the loop will break if i is no longer both less than nor equal to 5.
The simple change is to use i < 5.
The i <= 5 condition has to evaluate to false for the control to break the loop. And that happens when the value of i is 6.
because you start with zero or use <5 instead of <= if i=0
for (let i = 1; i <= 5; i++) {
console.log(i);
console.log("Hello World!");
}
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 2 years ago.
I can't figure out the output of the following two loops. The only difference I notice is that the former use var and assigns a global scope and later create a local scope using const.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1);
}
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1);
}
the output is 3 3 3 and 0 1 2.
According to my shallow knowledge, the first loop has to output 0 1 2.
If I print the value of i in the first loop.
for (var i = 0; i < 3; i++) {
console.log(i);
setTimeout(() => console.log(i), 1);
}
the output printed in the console by first console.log(i) is 0 1 2. While in the one wrapped within setTimeout vary.
Why?
var gets hoisted into the global scope, so when setTimeout is called it logs out whatever the value of i is when it is called, which would be 3 as the for loop has set i to 3 on its last iteration. Whereas let is scoped to the for loop and closes over the value of i on each iteration, thus printing 0 1 2.
How do we reason about these JavaScript statements and explain their output?
i = 1; i = i++; console.log(i); // Outputs 1 in Firefox
i = 1; x = i++ + i++; console.log(i, x); // Outputs 3 3 in Firefox
i = 1; console.log(i, i++); // Outputs 1 1 in Firefox
In C, the equivalent statements for (1) and (2) would be said to invoke undefined behavior because we are modifying the value of i more than once between two sequence points. In C, the equivalent statement for (3) would be said to invoke undefined behavior because the order of evaluation of function arguments is undefined. What are the rules in JavaScript?
As per the ECMA 5.1 Specification of Postfix Increment Operator,
Let lhs be the result of evaluating LeftHandSideExpression.
Let oldValue be ToNumber(GetValue(lhs)).
Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 11.6.3).
Call PutValue(lhs, newValue).
Return oldValue.
As per the rules, lets evaluate the expressions
i = i++
The value will be incremented and set in i. as per step 4 and 5. Then the oldValue 1 itself is returned and you are storing it again in i. That is why you are getting 1.
x = i++ + i++
The same logic. i++ evaluates to 1 and i is set to 2. Now, the next i++ is evaluated which evaluates to 2 and the value of i is set to 3. So the sum of 1 and 2 is assigned to x. That is why it prints 3 3
console.log(i, i++)
Again, the same logic. i is 1 and i++ evaluates to 1, but the value is set to 2 only. That is why it prints 1 1
I wonder why seemingly equal loops lead to the different results.
First loop
for (var i = 0; i < 5; i++) {
console.log(i);
}
Results:
0
1
2
3
4
The result is fully understandable and expectable behaviour.
However, the following loop
var i=0;
while ( i<5) {
console.log(i);
i++;
}
leads to the different results, such that
0
1
2
3
4
4
As a beginner in programming I don't really understand why it is so, what the source of discrepancy in this case.
If you change to
var i=0;
while ( i<5) {
console.log("i is " + i);
i++;
}
then you will see in the console that it does output the correct values "i is 0", 1,2,3,4. The console also outputs the value of the last evaluated statement, which is why you see an additional 4.
If I run the for example in Google Chrome it prints an additional undefined because it outputs the value of the last evaluated statement, which is the console.log.
I think what you are seeing is an extra value printed by the interactive Javascript console that is the "result" of this code snippet.
The Javascript console prints the result of the for() and while() expression . If you run the first loop console :
for (var i = 0; i < 5; i++) {
console.log(i);
}
The results will be :
0
1
2
3
4
undefined
Here it prints the value of var i which is local to the scope of the for() loop , hence undefined outside it.
In the second case , just the var i is defined outside the loop body , hence it prints the latest value of i which is not undefined.
Since it seems the snippets are being evaluated, as through eval() or a REPL/Console, the extra 4 is the loop's return value.
And, yes, loops have return values.
Return (normal, V, empty).
Though, it's not something that's particularly useful to you in most cases, as attempting to retrieve it normally gives you a lovely SyntaxError. :)
var a = for (var i = 0; i < 5; i++) i;
console.log(a);
SyntaxError: Unexpected token for
However, eval() the loop, and you can see it.
var a = eval('for (var i = 0; i < 5; i++) i;');
console.log(a);
4
The value returned, V, comes from the evaluation of the loop's Statement. In the above case, that's simply i;, which is 4 the last time.
For your snippets, the for loop's result is undefined from console.log(i); and the while loop's result is 4 from i++;