Explain why for loop behaves like this in JavaScript? [duplicate] - javascript

This question already has an answer here:
Javascript: When writing a for loop, why does it print the last index number?
(1 answer)
Closed 7 years ago.
Though I'm aware of closures and scopes. I need some detailed explanation on the following piece of code.
for (var i = 0; i < 10; i++) {
i // no console.log
}
Output
9
Why would it not display from 0 to 9 ?
Ran on chrome developer console.

Your question is a bit vague, but it seems you are asking why the output would end at 9, instead of 10 (even though, in your example, you provide no output method).
Your loop uses the < operator to compare i and the 10 constant, which translates to "less than 10". Since you are incrementing by whole numbers, 9 will be the last integer before your loop falls outside of the < 10 range, thereby breaking out of the loop.
If you are expecting 10 as your final output, you can use the "less than or equal to" operator (<=) to compare i and 10.
Edit
You've edited your original question, and the answer to it is best summed up in another Stack Overflow answer:
All statements in javascript have a value, including the block
executed in looping constructs. Once the loop block is executed, the
final value is returned (or undefined if no operations take place).
The statement that is implicitly providing the return value "100" is
numbers[i] = i+1;, as the final iteration of i+1 produces 100 and
assignment operations return the value being assigned.

If you're running that in the console, it's because the console shows the final result of the last statement in the program it runs.
In your case, the for loop gives a final value of 9.
While it may seem odd that I'm talking about a for statement giving a result (since statements don't give results), they actually do give a result with respect to the execution of the entire program. This result is obtainable by whatever is executing your code.
Here's an example. You can do the same with eval(), which will give you the result of the final statement.
var n = eval('for(var i = 0; i < 3; i++) {i}');
console.log(n);
This will give you 2 in the console as the result of the program eval'd even though the only result could come from the for loop, which returns the last statement result of its last loop.

Related

javascript function output problrm [duplicate]

This question already has answers here:
Difference between pre-increment and post-increment in a loop?
(22 answers)
Closed 1 year ago.
The output of console.log(in1()) should be 11 but it's 10 why?
function outer() {
let i = 10;
return function inner() {
return i++;
}
}
var in1 = outer();
console.log(in1());
Quoting https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment here:
If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.
Therefore, the postfix (that is, x++; postfix because it appears after) operator only gives the existing value before doing anything. That's why, when called, gives what exists, not what's the result of the addition.
Because of this, use the prefix operator instead, ++x, to get the value while still incrementing the variable.
The same applies to the decrement operator.
It's because using i++ returns i first, then adds 1 to i. If you call in1() the second time, you will see 11, 12 and so on.
Try using ++i instead.
When using the postfix syntax i++ the value is returned before incrementing. Use the prefix syntax instead ++i.

question about scope, closures and Let variables [duplicate]

This question already has answers here:
setTimeout in for-loop does not print consecutive values [duplicate]
(10 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
What is the difference between "let" and "var"?
(39 answers)
Closed 1 year ago.
I am reading about closures, and I found these small exercises that I solved by chance, but I don't understand why they work.
The exercise is :
for (var i = 0; i < 3; i++) {
setTimeout(function log() {
console.log(i); // What is logged?
}, 1000);
}
I get that 3 will be printed 3 times because the value captured by log() when the for() ends.
Additionally, it was asked how to fix it for the console to print 0,1,2, and I found (by chance, to be honest), that it works by doing :
for ( let i =0 ...
But I guess because Let is block scoped, but i don't really know how to explain it in simple words.
The variables defined with let are blocked scope which means once you go out of the bracket it loses its value and if you try to access it will throw you an error. So, when the for is running the, i present in the console.log() will store the value for it like 0,1,etc.
whereas in the var part the var will be stored in memory and when the timeout is about to expire it will access the variable i in the memory and print whatever is there for that variable at that time.

Query about closures and difference between var and let [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
How do JavaScript closures work?
(86 answers)
Closed 3 years ago.
I have previously posted on SO:
How would you set the following loop to log like below?
The answer was to change var to let.
I am currently learning javascript after having studied python for a few months. I just wanted to see where my analysis is going wrong as I am struggling to apply the concept of block scope and function scope here.
Here is the original code snippet:
for (var i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, i * 1000 );
}
What I do not understand is, if I delete the setTimeout function bit and end up with this:
for (var i = 0; i < 5; i++) {
console.log(i);
}
The output changes from
5
5
5
5
5
to
0
1
2
3
4
which was what I thought it should initially do. I don't understand why in the first case the need to use let i was necessary but in the second case it works fine with var.
Another point of confusion is that, if you take the first code snippet, with the setTimeout function, the value of the final i printed is 5. This does not make sense considering our initial for loop was only supposed to run till i<5.
The last point I am struggling with is that even if i was allowed to take on the value of 5, it seems the action (printing i) is done after the loop? I am saying this because i starts off at 0, and increases in value iteratively, here we are printing the final value of i 5 times. This must mean the computer has gone through the iteration before and then decides to do the action using the final value of i but 5 times?
Essentially I thought it goes as follows, we create a variable i using var, we say that as long as i is less than 5, do something, after doing something increase i by 1 and repeat.
Instead what it looks like from the first codes output is, create a variable i using var, i increases by 1 till i equals 5, do the action as many times as the number of iterations.
Sorry if this question is not coherent but I can't seem to apply the concepts of function scope and block scope here, which I feel is the key issue. Can someone please elaborate on this particular example?

Developer tools console logs 3 for a=3 and undefined for var a = 3 [duplicate]

This question already has answers here:
Why does JavaScript variable declaration at console results in "undefined" being printed?
(4 answers)
Closed 4 years ago.
In chrome Developer tools, when I type
a = 3 logs 3 but
var a = 3 logs undefined.
Why does the first statement return 3 but not the second one?
Because that's the way it is.
A statement beginning var is a declaration. Declarations don't, in and of themselves, have a value. They tell the computer to do something (to create a variable, optionally with some initial value).
But assignment expressions are different. a = b evaluates to (or "has") the new value of a, in order to allow chaining, such as a = b = c = d.
Could they have made it so that var a = b was an expression and evaluated to something? Sure, probably. But it would hold absolutely no useful value to butcher the language grammar in such a manner.
Read up about statements and expressions in programming languages.
Because undefined is the result of the var statement.
Statements don't actually have a "result" that can be used in your code, but a program has a final result, and your single line of code in the console is evaluated as a program.

JavaScript parentheses (1,2,3,4,5) [duplicate]

This question already has answers here:
Javascript expression in parentheses
(2 answers)
Closed 8 years ago.
I just came across some notation in JavaScript like so:
var a = (1,2,3,4,5);
This will always return the last value, in the above case 5. I'm aware of using brackets to namespace my JavaScript code, but have never seen it used this way.
Is there any use for this notation, or is it just some JavaScript byproduct?
It's the comma operator. As the mdn states (link) it always returns the later value. In your example it doesn't make much sense, since it will always assign a = 5. But consider this:
for (var i = 0, j = 9; i <= 9; i++, j--) {
...
}
It's used to increment and decrement in a single statement: i++, j--
Edit:
The parentheses in your example are necessary because its a variable declaration. In other cases they can be left out.
Parens are used to groups operations together. This is helpful for both setting operation precedence (e.g. x = (2+3) * 5 vs x = 2 + 3 * 5) and for making your code a little easier to read.
I suspect this is more a question about the comma operator. This is for making multiple assignments or operations on the same line. Here is a nice article about it: http://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/

Categories

Resources