0
A bit confused. Why does this output 0?
var x, y = 0; function change () { for ( x = 5; x < 10; x++) { ++y; } } alert (y);
6 ответов
+ 5
In your code, you have set your for loop inside of a function change. The problem is that you're not calling the function, therefore it is not running and the value of y is just going to default to 0.
+ 2
I don't know much JavaScript, but it looks like you've forgotten to call the function.
Out of curiosity, what does '++y' do?
+ 2
++y is something that is called a pre increment. What it does is it takes the value of y and increments it before using its value, the exact opposite of what y++ would do.
0
@immortal, I think I get it now.
There are 2 code blocks and the ++y is within the second code block.
For the second code block to read the y variable, there needs to be a y variable in first code block, whereas the y variable is only present in global scope & not the first functional scope.
correct me if I'm wrong, please.
0
@Brian I'm pretty sure that isn't the case, this should work just fine if you call the change()function.
@Thanks, so it seems that it only changes the value it returns. Then it shouldn't make a difference in this case right?