0

As someone new to js, I was playing with loops when I encountered some peculiar behavior with the following code:

var i = 5;

while(i!=0){
  console.log(i);
  i--;
}
OUTPUT: 543211

I replicated the same code in c++ :

int i = 5;

while(i!=0){
  cout<<i;
  i--;
}
OUTPUT: 54321

It'd help to know if I'm missing some important differences between the two languages.

imvain2
  • 15,480
  • 1
  • 16
  • 21
Anjishnu
  • 73
  • 5
  • 2
    Running your code in the above snippet doesn't include the last one. – imvain2 Aug 11 '20 at 19:01
  • 1
    I am getting 54321 in both cases. – BlackList96 Aug 11 '20 at 19:02
  • That said there are important differences between the way closures work in js/functional-coding & c++/procedural coding https://stackoverflow.com/questions/23277/what-is-the-difference-between-procedural-programming-and-functional-programming – admcfajn Aug 11 '20 at 19:03
  • Thanks! There's a similar question [here](https://stackoverflow.com/questions/35454291/javascript-while-loop-return-value). Think this query can be closed now. – Anjishnu Aug 11 '20 at 19:03

1 Answers1

6

If you run the code in the browser console, whatever the last statement evaluates to will log to the console as well. It's not actually getting console.log'd, though.

For example, if you do this:

var i = 5;

while(i!=0){
    console.log(i);
    i--; 
    '';
}

At the end of your list you will see ''

dave
  • 62,300
  • 5
  • 72
  • 93