Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 28, 2024 10:06 am GMT

Leave for loop now !

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...

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


Original Link: https://dev.to/sh20raj/leave-for-loop-now--10ih

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To