For... in vs For... of vs forEach JavaScipt | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

For... in vs For... of vs forEach JavaScipt

I need help with all these for loops. Here's what I think I know, tell me if I'm wrong. For... in | for (let x in array) {console.log(array[x]);} As the for loop ... loops? (iterates?), the variable between for and in keywords is the key or the index of the thing after the in keyword (in this case array, although it can be an object, etc). This is not recommended for arrays because it will output functions I think. I guess my confusion is functions in an Array. Arrays can have functions? Are they objects or can you give functions to data types? If they are objects wouldn't the functions be methods? Should I use for... of then? Thank you For... of | for (let x of array) {console.log(x)} As the for loop loops, the variable between for and of keywords is the value of the in index/keys of the container after the of keyword forEach is some kind of built in function that only works on arrays. True? False? How does it work? How is it different than the other for loops? I don't know much about forEach Thank you!!

25th Nov 2019, 7:50 PM
JJ McSquiggles
JJ McSquiggles - avatar
1 Answer
+ 4
https://code.sololearn.com/WhAgjnzzpOB0/?ref=app for in iterates over the keys of objects In JavaScript, array is a special type of object, with keys are numeric values 0, 1, 2.... for of iterates over the values of arrays or other iterables objects such as HTMLCollection and NodeList forEach is ES6 Array method. It accepts a function as argument. The function's first parameter is the element, optional second parameter is the index, optional third parameter is the array itself.
26th Nov 2019, 11:05 AM
Gordon
Gordon - avatar