Can you guess what will be the output of
let cars2 = [4,5];
//cars2.length = 100;
cars2.forEach((car) => {
console.log(car, "some text");
});
,
let cars2 = [];
cars2.length = 100;
cars2.forEach((car) => {
console.log(car, "some text");
});
and
let cars2 = [4,5];
cars2.length = 100;
cars2.forEach((car) => {
console.log(car, "some text");
});
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>
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...
but the read results are
(Can anyone explain why?)
Isn't it interesting 🤨.
Result
https://chat.openai.com/share/57c5e5a2-3250-4484-ac58-61623cad201e