Leave for loop now ! 🤔

Sh Raj - Mar 28 - - Dev Community

Can you guess what will be the output of

https://codexdindia.blogspot.com/

let cars2 = [4,5];
//cars2.length = 100;
cars2.forEach((car) => {
  console.log(car, "some text");
});
Enter fullscreen mode Exit fullscreen mode

,

let cars2 = [];
 cars2.length = 100;
cars2.forEach((car) => {
  console.log(car, "some text");
});
Enter fullscreen mode Exit fullscreen mode

and

let cars2 = [4,5];
 cars2.length = 100;
cars2.forEach((car) => {
  console.log(car, "some text");
});
Enter fullscreen mode Exit fullscreen mode

I tried to create a new way of looping in JavaScript, because I liked the forEach loop and I don't like the long formate of the for loop in js. I tried to invent a new way of looping so I search for loop javascript and edited this code.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Loop</h2>

<p id="demo"></p>

<script>
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
let text = "";
cars.length = 100;
for (let i = 0; i < cars.length; i++) {
  text += cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

This worked fine ( you can change to text += i + "<br>"; for getting counting )

the modification of array.length was working fine for the for loop.

but when I tried it with the forEach loop it's different. (a little bit obvious 😅) I thought I may be wrong at this but guess what even chatGPT given the wrong reply, it given the reply that I guessed at starting...

Image description

Image description

but the read results are

Image description

Image description

(Can anyone explain why?)
Isn't it interesting 🤨.

Result

Image description

https://chat.openai.com/share/57c5e5a2-3250-4484-ac58-61623cad201e

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .