I just want to know the difference between the two codes

var myArr = [ 2, 3, 4, 5, 6];
var total = 0;
 for (let item of myArr) {
     total += item 
}

for (var i=0;i<myArr.length;i++) {
    total += myArr[i] 
}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

Hi @praveen511!

Welcome to the forum!

Both loops do the same thing, it is just written a little differently.

For loops can be used for pretty much anything while for… of loops are good for arrays, strings and other array like objects.

You could also check out this article which gives a more in depth explanation.
https://blog.bitsrc.io/3-flavors-of-the-for-loop-in-javascript-and-when-to-use-them-f0fb5501bdf3