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

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using For Loops with Arrays

akak
akak
29,446 Points

What are the advantages of using variable?

I am wondering what are the advantages of using variable when the code still works written that way:

function printList(list){
  print("<ol>");
    for (i = 0; i < list.length; i++){
      print("<li>" + list[i] +"</li>");
    } 
  print("</ol>");
}

printList(playList); 

Outcome in HTML is exactly the same...

3 Answers

Because in this case, print is using document.write to update the HTML of the page. Every time you do that, the browser has to go through the new HTML again to determine what should be displayed to the user.

It is much more efficient use of resources to just change the value of a variable and then print the entire thing in one go.

If you use variables, you can make your code more clean and simple to you and others understand. Also, it's good practice.

Gary Calhoun
Gary Calhoun
10,317 Points

I think you can add the variables you declare inside multiple functions. Whereas yours is a one time use scenario. I could be wrong though... Variables are used for storing data though, and then you can carry that variable over from one function to another.