-2

In my example below, why does it log 512, rather than 1? I understand javascript is synchronous, so shouldn't the logging occur long before the for loop completes? For this reason, I was expecting result = 1 when logged.

let result = 1;
for (counter = 1; counter < 10; counter ++) {
    result = result * 2;
}
console.log(result);
  • 2
    Not sure if that's a typo, but re: " I understand javascript is synchronous": it *is* synchronous unless you do something async. That code is synchronous, so the code after the loop won't execute until the loop had finished. Everything would need to be a callback otherwise. – Carcigenicate Oct 06 '19 at 22:20
  • 1
    For the most part, most javascript expressions are sequential (synchronous), including loops. There are some asynchronous methods, such as `setTimeout`, `setInterval`, and `XMLHttpRequest` that are also initiated sequentially, but asynchronously wait for a return or callback. – CrayonViolent Oct 06 '19 at 22:24
  • Why would you expect that? The loop is executed before the log. – evolutionxbox Oct 06 '19 at 22:35

3 Answers3

1

Synchronous: Means that only one operation can be in progress at a time.

According to this definition your console.log() function will only be executed after your loop has finished executing.

If you want your code to run console.log() while executing your loop, you mean your code is asynchronous.

Guilherme Martin
  • 837
  • 1
  • 11
  • 22
1

The issue here is WHEN are you logging.

When you are logging the content of "result", the for-loop is completed, and the value of the "result" variable have been updated each iterations of the loop.

The following might illustrate this

let result = 1;
console.log(result);
console.log("loop start");
for (counter = 1; counter < 10; counter ++) {
    console.log(result);
    result = result * 2;
}
console.log("loop end");
console.log(result);

will give you the following result:

1
loop start
1
 2
 8
 16
 32
 64
 128
 256
loop end
 512
Antoine Claval
  • 4,923
  • 7
  • 40
  • 68
0

JavaScript synchronize that's mean is one thread work so this operation is iterative you can see this link for more information

regard :)