I’m trying to learn Javascript but I am stuck on this problem. I keep going around in circles and have been staring at this problem for hours. I can’t seem to find a solution that I can wrap my head around… Any help will be appreciated. I don’t understand how to get the output, there’s so much going on. It’s fun but I’m having a hard time lol
What exactly are you trying to do? Predict the output of that piece of code? Go line by line and expression by expression. Write down a timeline of the values of your variables.
line 1: msg = 'helloworld'
– assigns ‘helloworld’ to msg, msg is a string of length 10.
line 3: first for
loop
initialisation: var x=-2
– defines x
and sets its value to -2
test: x<msg.length-1
– test if x
(-2) is smaller than msg.length-1
(9). It’s true
so we enter the loop and execute the block
line 5: if (msg.length==5)
– false
: msg.length
is 10, not 5, so we skip the if
block lines 6 to 11 and we enter the else
block on line 12
line 15: enter a second for
loop
initialisation: var i=msg.length
– i
is defined and set to 10
test: i>(msg.length-1)
– is i
(10) > msg.length-1
(9)? true
so we execute the for
block
line 17: console.log(i)
– write 10 to the console
for
block for loop 2 is finished, we execute the incrementation part of the loop: i--
– i
is now 9
Then it’s the test again i>(msg.length-1)
– is i
(9) > msg.length-1
(9)? It’s false
so we exit loop 2.
There’s no more code in the for
block for loop 1, so we execute the incrementation part of the loop: x++
– x is now -1
Back to the test for loop 1: x
(-1) < 9? true
so we execute the for
block again
The if
condition will never evaluate to true
since msg
is not changed anywhere so we execute the else
statement again. Since all the code there depends on msg.length
, the result is the same: it outputs 10 to the console.
And it keeps doing that for every value of x
between -2 and 8 inclusive. It exits for
loop 1 when x
has been set to 9.
So what this piece of code does is output the number 10 eleven times. Unless I got something wrong somewhere.