James.DDD James.DDD - 2 months ago 11
Javascript Question

What does each line of this code do?

Hi guys I just started learning JavaScript and in one of the sort function examples it contains other things that I do not know what they do , can someone explain what each line does ? All help appreciated don't hate , help.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to sort the array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
fruits.sort();
document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>

Answer
var fruits = ["Banana", "Orange", "Apple", "Mango"]

This line creates an array which can be accessed by the word fruits and the array has been assigned to that variable. When we create an array we seperate each item of the array and wrap it with square brackets, this array values, "Banana", "Orange", "Apple" and "Mango".

document.getElementById("demo").innerHTML = fruits;

This will select the element with the id of demo and set its inner html to be your array.

function myFunction() {
    fruits.sort();
    document.getElementById("demo").innerHTML = fruits;
}

This creates a function which can be accessed using myFunction. When this function is run it will run the lines of code inside the function.

fruits.sort()

This will take the fruits array and run the sort function on it, which will sort the array alphabetically.

document.getElementById("demo").innerHTML = fruits;

This will get the element with the id of demo and set its innerHtml to be the fruits array, which will now be the sorted fruits array.

Further information:

Javascript Arrays: http://www.w3schools.com/js/js_arrays.asp

Array's Sort Function: http://www.w3schools.com/jsref/jsref_sort.asp

Comments