I'm trying to understand the basics to have solid foundations.
At the moment I'm doing an exercise to recover some fictitious tweets. I am making an effort to understand well the reason of all the development of the loop and I have something left without understanding.
I put here the initial code, the functional one:
var tweets = ["Hi", "Bye", "See You"]
var dailyTweets = "";
for (var i = 0; i < tweets.length; i++) {
dailyTweets = dailyTweets + "<p>" + tweets[i] + "</p>";
}
document.getElementById("tweet").innerHTML = dailyTweets;
console.log(dailyTweets);
<div id = "tweet"></div>
Analyzing the code I said to myself: It seems to me that the line dailyTweets = dailyTweets + "<p>" + tweets[i] + "</p>";
could be dailyTweets = "<p>" + tweets[i] + "</p>";
and still work, even better because it would be more concise. The result is the following:
var tweets = ["Hi", "Bye", "See You"]
var dailyTweets = "";
for (var i = 0; i < tweets.length; i++) {
dailyTweets = "<p>" + tweets[i] + "</p>";
}
document.getElementById("tweet").innerHTML = dailyTweets;
console.log(dailyTweets);
<div id = "tweet"></div>
This code did not work, since the expected output is each tweet separately and in sequence, as in the first example.
My question is: Why should I put the variable must be equal to the variable plus the index of the array to make it work; ex. var = var + "<p> array[i] </p>"
?
Why this yes: dailyTweets = dailyTweets + "<p>" + tweets[i] + "</p>";
and
This is not: dailyTweets = "<p>" + tweets[i] + "</p>";