In JavaScript, functions are objects because they can have properties and methods. What distinguishes them from other objects is that functions can be called. A JavaScript function is a block of code designed to perform a particular task perform a particular task and the function is executed when it is called. Functions can be built-in or user defined.
Example of a user defined function:
JavaScript has a number of standard, built-in objects with methods and properties. Some of these are described below:
You can find more built in methods from the w3schools reference guide .
This example is a function called calculateTotal(). The function uses a for loop to prompt a user to input any number 5 times. Each time the user enters a number, it is stored in an array. The function then calculates the sum (total) of the inputted numbers by using a while loop and adds the output to the <p> tag with an id of functionExample in the HTML file.
HTML file: the onclick event defined in the "Try this function!" button element below, calling calculateTotal() function.
JS file: the calculateTotal() function is called when the event is triggered (i.e. the button is clicked).