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.

4
  • 2
    Running your code in the above snippet doesn't include the last one. Commented Aug 11, 2020 at 19:01
  • 1
    I am getting 54321 in both cases. Commented Aug 11, 2020 at 19:02
  • That said there are important differences between the way closures work in js/functional-coding & c++/procedural coding stackoverflow.com/questions/23277/… Commented Aug 11, 2020 at 19:03
  • Thanks! There's a similar question here. Think this query can be closed now. Commented Aug 11, 2020 at 19:03

1 Answer 1

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 ''

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.