My first javascript sorting I started learning JavaScript a week ago, and I made a sorting function on my own. It does work, but I need reviews and how to write a better one.

&lt;body&gt;
&lt;ul id="list"&gt;
    &lt;li&gt;Art&lt;/li&gt;
    &lt;li&gt;Mobile&lt;/li&gt;
    &lt;li&gt;Education&lt;/li&gt;
    &lt;li&gt;Games&lt;/li&gt;
    &lt;li&gt;Magazines&lt;/li&gt;
    &lt;li&gt;Sports&lt;/li&gt;
&lt;/ul&gt;

var list = document.getElementById("list");
var myList = list.getElementsByTagName("li");
var a = [];
for (var i = 0; i &lt; myList.length; i++) {
    a[i] = myList[i].innerHTML;
}
a.sort();
for (var i = 0; i &lt; myList.length; i++) {
    myList[i].innerHTML = a[i];
}


Output:


  
  Art
  Education
  Games
  Magazines
  Mobile
  Sports
Some notes:


var myList: Don't use generic names like myList. My list of what? Variable names are very important, they should inform about the nature of their content, not their type (although it's indeed important to use singular variable names for single elements and plurals for collections).
var myList = list.getElementsByTagName("li");. What if list is null? no checks?
myList[i].innerHTML = a[i];. You are overwriting HTML contents, it would probably be better to move DOM elements instead.


I'll leave a pure Javascript re-write to others, if you are interested in solutions that use external libraries, using jQuery and underscore I'd write:

var sorted_lis = _.sortBy($("#list li"), function(li) { return li.innerText; });
$("#list").empty().append(sorted_lis);


The original ten lines reduced to two (one actually, but it's good to break things a bit and give names to intermediate values), thanks to functional style (underscore) and easy DOM manipulation (jQuery).