Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
HanJoon Kim
Full Stack JavaScript Techdegree Student 15,388 PointsI don't understand the syntax of ES2015 for loop <Introducing ES2015 - Object Property Shorthand>
use strict';
function submit(name, comments, rating = 5) {
let data = { name, comments, rating };
for (let key in data) {
console.log(key + ':', data[key]);
}
// … do ajax request
}
submit('English', 'Great course!');
From the above code, the syntax for "for-loop" has never been explained along the course. Could anyone please explain the syntax?
1 Answer
Samuel Ferree
31,723 Pointsa for loop is generally used to loop through a list of items. In some languages the idea is sometimes know as a "foreach" loop, and that makes the idea clearer. consider in C#
int[] nums = { 1, 2, 3, 4, 5 };
foreach(int num in nums)
{
Console.WriteLine(num);
}
The idea is similar in javascript, given a collection, the loop will iterate over the collection, and complete the block of code one time, for each value in it. so in javascript
let words = [ 'hello', 'how', 'are', 'you?' ];
for(let word in words) {
console.log(word);
}
// output:
// hello
// how
// are
// you?
When javascript does a for loop on an object "{}" instead of an array "[]", it loops over each key or propertyname in the object. so the loop in your example is run 3 times, once with key = 'name', once with key='comments', and finally with key='rating'.