DEV Community

Sh Raj
Sh Raj

Posted on

Leave for loop now ! πŸ€”

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

Top comments (1)

Collapse
 
elmonty profile image
elmonty

for...of loops are more readable than forEach() and have practically the same amount of code. A for...of loop is slightly more performant because forEach() has to execute a function call on every iteration.

cars.forEach(car => {
    console.log(car);
});

for (let car of cars) {
    console.log(car);
}
Enter fullscreen mode Exit fullscreen mode