Variable and Loop in JavaScript

Question:

I'm trying to understand the basics to have a solid foundation.

At the moment I am doing an exercise to recover some fictitious tweets. I am making an effort to understand well the why 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>"; it could be dailyTweets = "<p>" + tweets[i] + "</p>"; and still work, even better because it would be more concise. The result is as follows:

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, as the expected output is each tweet separately and in sequence, as in the first example.

My question is: Why should I place the variable must be equal to the variable plus the index of the array for it to work; ex. var = var + "<p> array[i] </p>" ?

Why this yes: dailyTweets = dailyTweets + "<p>" + tweets[i] + "</p>";

Y

Not this one: dailyTweets = "<p>" + tweets[i] + "</p>";

Answer:

dailyTweets = dailyTweets + "<p>" + tweets[i] + "</p>";

What this line means is, " dailyTweets now is what this new text already had more".

dailyTweets = "<p>" + tweets[i] + "</p>";

And this one says " dailyTweets is now this new text."

That is the difference, in the last one you are overwriting the content of the variable, the operator = assigns to the left side what happens from the right side, it does not add.

There is a more compact way to do what you want, with the operator += which is shorthand for the first form:

dailyTweets += "<p>" + tweets[i] + "</p>";
Scroll to Top