DEV Community

Cover image for Guess the output of this JS code
Shuvo
Shuvo

Posted on

Guess the output of this JS code

Try to guess the output of this code without running it. Let me know in the comment what you got πŸ˜‰

let num = 10;
for(let i = 0; i < num; i++){
    console.log(num);
    num--;
}
Enter fullscreen mode Exit fullscreen mode

hint: You may have got the first half right

Latest comments (16)

Collapse
 
gamer1478 profile image
Aayush Garg

10
9
8
7
6
this should be the output.

Collapse
 
0shuvo0 profile image
Shuvo

Yes, It was just a trick question for newbies

Collapse
 
janpauldahlke profile image
jan paul

a unicorn bookmark well earned. ty for this.

Collapse
 
0shuvo0 profile image
Shuvo

Many many Thank s πŸ’“

Collapse
 
abdelrahman_dwedar profile image
β€˜AbdelraαΈ₯man Dwedar πŸ‘¨πŸ»β€πŸ’»πŸ‡΅πŸ‡Έ

Nice one!

The solution is:
10
9
8
7
6

The explanation:
1- It'll output 10 since we didn't change it yet.
2- We'll increase i to 1 and num decreased to 9.
3- Increases i to 2 and num decreased to 8.
4- Increases i to 3 and num decreased to 7.
5- Increases i to 4 and num decreased to 6.
Then it ends, 'cause num will be 5 while i will be the equal, so it stops.

Collapse
 
fjones profile image
FJones

Output (i/num after iteration):
10 (1/9)
9 (2/8)
8 (3/7)
7 (4/6)
6 (5/5) - loop terminates as !(i < num).

Collapse
 
deeyestea profile image
deeyestea

10, 9, 8, 7, 6

Collapse
 
0shuvo0 profile image
Shuvo

Correct

Collapse
 
thiennguyen1tiki profile image
thien-nguyen1

10, 9, 8, 7, 6
for loop stop when num = 5, ( every console.log in for decrease num for 1 )

Collapse
 
0shuvo0 profile image
Shuvo

right

Collapse
 
path08 profile image
PATH

Is it uhmm

10
9
8
7
6

Collapse
 
0shuvo0 profile image
Shuvo

Correct

Collapse
 
rexion21 profile image
Gerardo Leonel Blesly

10
9
8
7
6
5
4
3
2
am i correct?

Collapse
 
0shuvo0 profile image
Shuvo

Thanks for trying. but actually its wrong