The way I was taught maths in high school is that 0 plus any number is that number but in this code, that's not the case. Why?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 10

The way I was taught maths in high school is that 0 plus any number is that number but in this code, that's not the case. Why??

for(i=0; i<5; i++) { i += i; document.write(i); i++; }

28th Jun 2019, 5:19 PM
eMBee
eMBee - avatar
30 Answers
+ 20
for (i = 0; i < 5; i++) { // i=0, i=2, i=6 i += i; // i = 0+0 = 0, i = 2+2 = 4 console.log(i); //Output -> 0 -> 4 i++; // 0++, 4++ }
28th Jun 2019, 6:57 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 13
*Part 1: Review a Simpler Version* Let's first imagine if the following lines were removed: Line 2: i+=i; Line 4: i++; The only line remaining in the loop block is: Line 3: document.write(i); Ask yourself, how many times would this line be executed and what do you expect the output to be? Based on Chris' explanation, you would know this line will be called 5 separate times and each time it's called, the values of `i` will respectively be: 0, 1, 2, 3, 4. Now, which option below did do expect the output to be? Output Option 1: (With Line Breaks) 0 1 2 3 4 Output Option 2: (No Line Breaks or Spaces) 01234 If the code was written like the following, you would see line breaks as seen in Option 1. document.write(
quot;{i}<br>"); However, without any block HTML tags, the characters will appear on the same line as in option 2. (continued...)
28th Jun 2019, 10:51 PM
David Carroll
David Carroll - avatar
+ 12
Enlightening explanations here from David Carroll Ed Briones all comes down to an assignment operator (+=), an output method (write) and two increment posfixes (x++). Loop One: 0 += 0 equals 0, then print 0, finally increment twice to initial value 0 + 2 = 2 Loop Two: Loop 2 += 2 equals 4, then print 4, finally the loop ends because the next loop is false. There is nothing wrong with the JS Math here. (= You can test these chunk of codes in a debugger like Chrome Devtools. This will allow you to know how your code is operating step-by-step, beyond being one genuine tool to find bugs. You will need to set the HTML/JS files in your favorite text editor/IDE, insert the keyword "debugger;" (without quotation marks) right before your target code, hit F12 to open debugger (or it can open automatically after activating it with this keyword) and then click F9 to step through each process, or F10 to hop into the next function, for instance. That's it. You will get familiar with your code logics way better.
29th Jun 2019, 12:30 AM
Luis Febro 🇧🇷
Luis Febro 🇧🇷 - avatar
+ 10
*Part 2: Continued...* How do you think the loop behavior would be affected if `i` was also incremented within the loop block, as seen first on Line 2 and then on Line 4 from the review in Part 1? - The value of `i` is increasing much faster in Part 2, which means the break condition will be reached much quicker and some numbers will be skipped. Now... this is where Chris C.'s answer comes into play. //The state of i in Loop 1: - Initial Value Entering Loop: i = 0 - Line 2 Rewritten: i = 0 + 0 - Line 3 Outputs: "0" - Line 4 Rewritten: i = 0 + 1 - i is now 1 - i++ in for loop Rewritten: i = 1 + 1 - i is now 2 - Break Condition Checked: 2 < 5 ✅ //The state of i in Loop 2: - Initial Value Entering Loop: i = 2 - Line 2 Rewritten: i = 2 + 2 - i is now 4 - Line 3 Outputs: "4" - Line 4 Rewritten: i = 4 + 1 - i is now 5 - i++ in for loop Rewritten: i = 5 + 1 - i is now 6 - Break Condition Checked: 6 < 5 ❌ Loop breaks after only 2 loops resulting with 04.
28th Jun 2019, 11:41 PM
David Carroll
David Carroll - avatar
+ 9
Mofey and Yusuf... As Diego and Chris C. mentioned, this has nothing to do with how JS starts counting array positions from zero - a.k.a zero-based languages. I think Diego did a great job explaining the reason this code outputs "0" and "4", which appear to be on the same line and looks like "04". Chris did a great job of breaking down the mechanics of a for loop in a general sense to supplement Diego's solid explanation. When I get a moment, I'll try to expand or recap on their really good explanations to try to address any possible disconnect you are still struggling with. 😉
28th Jun 2019, 10:31 PM
David Carroll
David Carroll - avatar
+ 9
Never is enough for many explanations on the same topic. This is actually very good because you have different perspectives from different learning backgrounds and additional resources. A truly learning marathon. If you forget one, you brain's neurons will struggle to find other, beyond linking up things better. =)
29th Jun 2019, 12:32 AM
Luis Febro 🇧🇷
Luis Febro 🇧🇷 - avatar
+ 8
Mofey You were taught correctly, but remember that the value of "i" changes and that rule won't apply anymore. First iteration (i == 0): // This is the rule i += i; // i == 0 + 0 == 0 document.write(i); // 0 // The value changes so it doesn't apply anymore i++; // i == 1 Second iteration (i++, i == 2): // You're no longer adding 0 i += i; // i == 2 + 2 == 4 document.write(i); // 4 i++; // i == 5, loop stops
28th Jun 2019, 6:26 PM
Diego
Diego - avatar
+ 8
for ( var i = 0; i < 5; i++ ) It is right: I will try to explain for: = loop through a block of code a number of times var i = 0: set varible to 0 before loop starts ( i is equal to 0) i > 5: defines the condition for the loop to run (i must be less than 5) loop until the condition is met. 1++ : increment the number by 1 each time the code block in the loop has been executed Output: The number is 0 + 1 The number is 1 + 1 The number is 2 + 1 The number is 3 + 1 The number is 4 It stops looping because 4 is less than 5 So this is still true to what you have learned. 0 plus the number is that number
28th Jun 2019, 8:11 PM
Chris Coder
Chris Coder - avatar
+ 8
Mofey Yusuf It has nothing to do with JS being zero-based. Please take a look at Danijel's answer to see how "i" increments. The values "i" takes at the beginning of each iteration aren't (0, 1, 2, 3, 4) but (0, 2, 6).
28th Jun 2019, 8:44 PM
Diego
Diego - avatar
+ 8
Chris C. Honestly... If they couldn't understand it based on the explanations you guys already posted, I'm not sure how else I could have helped. 🤷‍♂️
29th Jun 2019, 12:02 AM
David Carroll
David Carroll - avatar
+ 8
0+0==0
29th Jun 2019, 2:11 AM
Sonic
Sonic - avatar
+ 7
*Part 2: Review the Original Code* Let's approach this in reverse order. We know the output is: 04 If the code was written with line breaks, the output would have been: 0 4 Ask yourself, how is this different from the review in Part 1 and how would lines 2 and 4 cause this difference to occur. - Bear with me as I start with the most obvious difference: # 1, 2, and 3 are not displayed in this version of the code. What does this tell you about the number of times the loop actually called `document.write(i)`? - It was only called 2 times, instead of 5 times. How is the value of `i` changed in Part 1: - In part 1, `i++` enclosed within the for loop parentheses increments the value for `i` by 1 after the loop block of executed. This is why the loop block is executed 5 times. (Part 2 continued...)
28th Jun 2019, 11:22 PM
David Carroll
David Carroll - avatar
+ 7
Mofey / Yusuf I took this reverse approach to help you learn how to figure this out on your own. If you are still confused, read all the answers again and try to make sense of each point being made. Then, try this approach with another code that doesn't make sense. It's all about asking yourself the right questions based on your observations. Sometimes it helps to simplify the code and compare the differences to understand what is happening. Hopefully, this was a helpful tip that goes well beyond just this specific problem.
28th Jun 2019, 11:48 PM
David Carroll
David Carroll - avatar
+ 7
Luis Febro 🇧🇷 Nice explanation on your part as well. 👍 Regarding the use of the debugger statement... I hadn't used that in many years and was surprised to see it still in use. Do you prefer this over applying breakpoints? In any case, I completely agree the best way to accelerate learning is to dig into the code with a live debugger where your can step through the code one line at a time.
29th Jun 2019, 2:36 AM
David Carroll
David Carroll - avatar
+ 6
Sorry, didn't mean to confuse you, Yusuf, But saying js is 0 based doesn't explain why the answer is 4 example for(i=0; i<5; i++) {document.write(i);} the result is 0,1,2,3,4 but If you do this for(i=1; i<5; i++) {document.write(i);} then the output is 1,2,3,4 but what if I do this? for(i=0; i<=5; i++) { document.write(i);} then the output is 0,1,2,3,4,5 I attempted to explain what each part of the code meant. Instead of only writing more confusing code.
28th Jun 2019, 8:53 PM
Chris Coder
Chris Coder - avatar
+ 6
Luis Febro 🇧🇷 thanks for the debugger tip.
29th Jun 2019, 12:39 AM
Chris Coder
Chris Coder - avatar
+ 6
Breakpoint is another alternative too, especially to handle coding errors directly in the debugger. They managed to develop a more full blown tool which have this feature now, maybe Devtools was more basic when you tested. I use both techniques mainly. I learned about these practices reading some Devtool documentation/article so that I could learn some better practices. These breakpoints can be set to a range of other breakpoint methods like using to check Event listeners, DOM, in-line conditionals to trigger a step-by-step analyses and XHR/Fetch. Here is an article with introductory analisys on Devtools chrome. https://developers.google.com/web/tools/chrome-devtools/javascript/breakpoints Which debugger do you currently use, David Carroll ? I think this debugger very practical, but certainly there are great debuggers out there and I could be missing out on some extra features.
29th Jun 2019, 8:48 AM
Luis Febro 🇧🇷
Luis Febro 🇧🇷 - avatar
+ 5
Diego, why is `i` not 1 in the first iteration since `i` is 2 in the second iteration or why is `i` not 1 in the second iteration since the value of `i` at the end of the first iteration is 1?
28th Jun 2019, 8:04 PM
eMBee
eMBee - avatar
+ 5
Explanation loop by loop, line by line: for(i=0; i<5; i++) { i += i; document.write(i); i++; } 1st iteration line by line • i is initialized with 0 // i =0 • i, which is 0, is added with 0 // i=0 • value of i = 0 is printed // i=0 • increment i=0 by 1 // i=1 2nd iteration • i=1 is incremented to 2 // i = 2 • i, which is 2, is added with 2 // i=4 • Value of i = 4 is printed // i=4 • increment i = 4 by 1 // i=5 3rd iteration • i=5 increment to 6, is NOT <5 so loop ends // Hope this helps.
28th Jun 2019, 11:26 PM
Ed Briones
Ed Briones - avatar
+ 5
Luis Febro 🇧🇷 I remember a time when there were no JS debuggers. 😳 Then, when the earliest debuggers were created, they were only good with basic Javascript. 😳 Then Jetbrains released a JS debugger that actually worked. 😁 And the rest of the tools must have eventually caught on and got their debuggers to work. 🤩 And now I don't think about those dark days where you had to write JS without a debugger. 🤣😂 Seriously though, I live in the Developer Tools, PhpStorm, or VS Code for JS debuggers. I think PhpStorm is still the best experience for me. 😉
29th Jun 2019, 2:45 PM
David Carroll
David Carroll - avatar