A bit confused. Why does this output 0? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

A bit confused. Why does this output 0?

var x, y = 0; function change () { for ( x = 5; x < 10; x++) { ++y; } } alert (y);

18th Mar 2018, 4:46 PM
Briaה‎
5 Answers
+ 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.
18th Mar 2018, 4:52 PM
Faisal
Faisal - avatar
+ 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?
18th Mar 2018, 5:42 PM
Just A Rather Ridiculously Long Username
+ 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.
18th Mar 2018, 5:47 PM
Faisal
Faisal - avatar
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.
18th Mar 2018, 7:57 PM
Briaה‎
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?
18th Mar 2018, 8:13 PM
Just A Rather Ridiculously Long Username