Why Functions?

You can reuse code: Define the code once, and use it many times. You can use the same code many times with different arguments, to produce different results. For example, this function can be used everytime you want to convert Fahrenheit to Celsius:

  function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);

HTML file: Displayed by browser:
<body>
<p>This example calls a function to convert from Fahrenheit to Celsius:</p>
<p id="demo"></p>
<script>
function toCelsius(f) {
    return (5/9) * (f-32);
}
   document.getElementById("demo").innerHTML = toCelsius(77);
</script>
</body>

This example calls a function to convert from Fahrenheit to Celsius:

The toCelsius refers to the function object, while the toCelsius() refers to the function result.

BackTable of ContentsNext