Search code examples
javascriptasynchronousexecutionsynchronous

How JavaScript for loop executed?


The code after for loop is executing before the for loop on top. Javascript is executed synchronously, why it is executing line after for loop first?

function solution(A) {
  let diff = [];

  for (let i = 1; i < A.length; i++) {
    let sum1 = 0;
    let sum2 = 0;

    for (let j = 0; j < i - 1; j++) {
      sum1 += A[j];
      console.log('Why this is executing later? ' + sum1);
    }

    for (let k = i; k < A.length; k++) {
      sum2 += A[k];
    }

    console.log('Why this is executing frist? ' + sum1);
    diff.push(Math.abs(sum1 - sum2));
  }

  return Math.min(...diff);
}

solution([1,2,3,4,5]);


Solution

  • The first time your outer loop runs, i will be 1. Your inner loop checks if j<i-1, and j starts at 0. So the first time your inner loop executes, it will check if 0 < 0, which is false, and will immediately exit, and not perform the inner loop.