First, having your code indented properly and not taking advantage of optional syntax (braces and semi-colons) will go a long way towards your understanding of how the code is processed. Technically, curly braces are not required with for
and if
statements if there is just one statement to perform within the loop or within the branch of the if
. Additionally, JavaScript technically does not require that you place a semicolon at the end of your statements. Do not take advantage of either one of these optional syntaxes as it will only make things more confusing and possibly lead to bugs in your code.
With that in mind, your code really should be written as follows. The job of this code is to sort the items in the array. It does this by looping through the array and always checking the current array item and the item that precedes it. If the items are out of order, the values are swapped.
Please see the comments for descriptions of what each line does:
// Declare and populate an array of numbers
var a = [1, 7, 2, 8, 3, 4, 5, 0, 9];
// Loop the same amount of times as there are elements in the array
// Although this code will loop the right amount of times, generally
// loop counters will start at 0 and go as long as the loop counter
// is less than the array.length because array indexes start from 0.
for(i=1; i<a.length; i++){
// Set up a nested loop that will go as long as the nested counter
// is less than the main loop counter. This nested loop counter
// will always be one less than the main loop counter
for(k=0; k<i; k++){
// Check the array item being iterated to see if it is less than
// the array element that is just prior to it
if(a[i]<a[k]){
// ********* The following 3 lines cause the array item being iterated
// and the item that precedes it to swap values
// Create a temporary variable that stores the array item that
// the main loop is currently iterating
var y = a[i];
// Make the current array item take on the value of the one that precedes it
a[i]= a[k];
// Make the array item that precedes the one being iterated have the value
// of the temporary variable.
a[k]=y;
}
}
}
alert(a);