Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does anyone know why this is infinite loop?

var arr = [1,2,3,4,5]
for (var i = 2; i < arr.length; i++) {

    [arr[i], arr[i+1]] = [arr[i+1], arr[i]]
    
}

console.log(arr);

I have no idea why this is an infinite loop..

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Executing this will give you a sense of what happens.

async function inifiniteLoop() {
  var arr = [1, 2, 3, 4, 5];
  for (var i = 2; i < arr.length; i++) {
    [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
    console.log(arr);
    console.log(`i: ${i}; arr.length: ${arr.length}`);
    await sleep(2000);
  }
}

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

(async () => await inifiniteLoop())();

While you would get an IndexOutOfBounds exception in Java and many other languages this works in JavaScript.

const array = [34]
console.log(array)
array[3] = 23
console.log(array)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading