Yes, there is a difference between for loop and for/in loop in javascript. Here is what is different
consider this array
var myArr = ["a", "b", "c"];
Later, I add an element to this array, but in a different way, like so:
myArr[myArr.length + 1] = "d";
At this point of time, this is what the array looks like, if you console.log it
["c", "b", "a", undefined × 1, "d"]
Now, let us loop through the array using for and for/in loop and see what the difference is:
first, lets try the for loop
for(var i = 0; i != myArr.length; i++) { // note, i used " != " instead of " < ". Yes this is faster.
console.log(myArr[i]);
}
// output will look like this:
// "a"
// "b"
// "c"
// undefined × 1
// "d"
// - This still shows the undefined value in the array.
Now, lets look at the for/in loop
for(key in myArr) {
console.log(myArr[key]);
}
// array will look like:
// "a"
// "b"
// "c"
// "d"
// This will skip the undefined value.
Difference 1: The javascript interpreter will skip all values that are null or undefined when using the for/in loop. Also, the for/in loop will convert all values if it encounters a primitive value, to its equivalent wrapper object. Where as the for loop doesn't do this.
Difference 2: When using the for loop, we declared the variable i within the loop, this variable will be scoped within a function, if the for loop is written within that function. Which means, until the function ends, the variable i is still available, even outside of the for loop, but within that function. Where as, in case of the for/in loop, the scope of the "key" variable dies immediately after the for/in loop stops executing, which means, there is less memory utilization.