Aleksey Posted February 15, 2018 Report Share Posted February 15, 2018 I have two question about JS loops. Its about while loops. 1)if we type this line of code target.innerHTML = "LoopCount: " + loopCount + "<br>" + target.innerHTML; why does it write from lowest number to highest like this? LoopCount: 1 LoopCount: 2 LoopCount: 3 LoopCount: 4 LoopCount: 5 The function tells that starting loop is 5,we are targeting empty paragraph with id "target", then writting into it some text and saying that we want to see current loop number, which is 5 at the beginning , then we are substracting 1 from it(decrementing), and repeating, writing and so on again, so why doesnt it goes backward, 5,4,3,2,1? Why the first number is 1 when the starting was 5? My logic tells me if you start with 5, then print current number and then decrement it, and repeat it again all over , it should go in 5,4,3,2,1 order. function doItAgain(message) { var loopCount = 5; while(loopCount > 0) { var target = document.getElementById("target"); target.innerHTML = "LoopCount: " + loopCount + "<br>" + target.innerHTML; console.log("LoopCount is now: " + loopCount); loopCount = loopCount -1; } console.log("End loop"); var button = document.getElementById("looper"); button.value ="Done looping!"; 2) if we look at opposite case and write target.innerHTML = "target.innerHTML + "LoopCount: " + loopCount + "<br>" ; then it writes LoopCount: 5 LoopCount: 4 LoopCount: 3 LoopCount: 2 LoopCount: 1 But if we look the order into syntax, shouldnt it write this? 5 LoopCount: 4 LoopCount: and so on.... Quote Link to comment Share on other sites More sharing options...
administrator Posted February 15, 2018 Report Share Posted February 15, 2018 It makes sense because loopCount is in quotes: "LoopCount: " ... So JS sees that as a string datatype. Makes sense? Quote Link to comment Share on other sites More sharing options...
Aleksey Posted February 15, 2018 Author Report Share Posted February 15, 2018 I understand that but if we start with 5 then print on the screen current number, and then substract 1 from it, and repeat cycle, why isnt order 5,4,3,2,1 there? instead it goes from 1. Quote Link to comment Share on other sites More sharing options...
administrator Posted February 15, 2018 Report Share Posted February 15, 2018 Try changing this: target.innerHTML = "LoopCount: " + loopCount + "<br>" + target.innerHTML; To: target.innerHTML = target.innerHTML + "LoopCount: " + loopCount + "<br>"; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.