At this point, it’s time point the for-in loop to the test. In your challenge, I want you to take the sentence, this space for rent and put each word in a list. Then, I want you to loop through that list using a for-in loop. Take each word and combine it into a sentence and then print out the sentence after the loop.
If you are feeling like doing some extra credit, then implement the same thing only this time, using a regular for-loop. Pause the video now, and give it a shot.
How’d that challenge go for you? Hopefully, you didn’t find it too hard. Feel free to follow along with me. Start by opening a new instance of dartpad. We’ll start be creating our list of words.
var words = ['this', 'space', 'for', 'rent'];
Now let’s create a variable to store the sentence.
var sentence = '';
Okay, now let’s loop through each items in the list and add it to the sentence. We’ll do this by creating the for-in loop.
for (var word in words){
}
Now lets add it to the sentence.
for (var word in words){
sentence += '$word ';
}
This is just one way to write this line of code. The space after the word makes sure that words aren’t squished together. Now let’s print out the sentence.
print(sentence);
Now let’s run it. Look at that - we get our sentence. If we select the sentence, you’ll that there is a space after the last word. There are ways to get rid of that space, but let’s not go down that rabbit hole right now. Let’s implement the same thing using a for-loop. First, let’s create another sentence.
var anotherSentence = '';
Now lets loop through our list using our for-loop.
for (var i=0; i < words.length; i += 1) {
}
Now lets construct our sentence using our list.
anotherSentence += '${words[i]} ';
Finally, let’s print out our new sentence.
print(anotherSentence);
And that’s it - run the program. And this time, it prints out the same thing. You’ll see that the for-loop is a bit clunkier than the for-in loop. In general, it’s a good idea to use the for-in loop unless there’s a very good reason not to