0

These two javascript while-loops are absolutely identical. But, once we remove 'console.log('end')' after one of them, it will spit out extra '41' number in Chrome console and in Node.js v14.8.0. Is it what is called 'a side effect'?

// While-loop 1
const max = 40, min = 30;
let i = min + 1;
while (i < max) {
  console.log(i);
  i += 2;
}
console.log('end');
// 31 33 35 37 39

// While-loop 2
const max = 40, min = 30;
let i = min + 1;
while (i < max) {
  console.log(i);
  i += 2;
}
// 31 33 35 37 39 41
Maksym Dudyk
  • 1,082
  • 14
  • 16
  • 5
    I don't see a difference when running these. – VLAZ Feb 27 '21 at 08:36
  • 1
    I can verify that there is an extra "41" printed *if the latter code is run in the console*. This might be a bug. – kol Feb 27 '21 at 08:38
  • I run these two while-loops in Chrome dev tool and there is a difference. – Maksym Dudyk Feb 27 '21 at 08:38
  • The extra "41" is also printed if the code is run in a node console (tested in v14.8.0). – kol Feb 27 '21 at 08:40
  • 1
    That's the return value of the assignment. `console.log` would return `undefined` – VLAZ Feb 27 '21 at 08:40
  • @VLAZ Yes, but why is it printed? It's a little confusing. – kol Feb 27 '21 at 08:42
  • 2
    @kol because in a REPL environment, you always get the last returned value printed. – VLAZ Feb 27 '21 at 08:42
  • @VLAZ I know that, and it's OK if you type a simple assignment and hit Enter, but I find this behavior strange when I type in a more complex expression, like a loop with multiple assignments... (that was my case few days ago). I also don't remember Chrome REPL behaving this way in the past *in case of more complex expressions*. – kol Feb 27 '21 at 08:46
  • Hmm... I was wrong. I tested this phenomenon in Chromium 69 and it also printed the extra "41". – kol Feb 27 '21 at 08:48
  • 3
    @kol you'd still get the *last* value. That's always been the case. At most, you might get `undefined` if the last thing was a statement only code like `let x = 42` - then you'd get `undefined` because there is no return value. – VLAZ Feb 27 '21 at 08:48
  • 1
    @VLAZ Thanks for the clarification. I think you should write an answer! – kol Feb 27 '21 at 08:50
  • @kol and VLAZ, I agree. Thank you! – Maksym Dudyk Feb 27 '21 at 08:56

0 Answers0