Your browser does not support JavaScript!
Upvotes Anonymous 1 User 1

Introduction to JavaScript Functions

Below is an HTML page with some JavaScript:
<!DOCTYPE html>
<html>
<head>
  <title>My Page</title>
</head>
<body>

<script>
alert("Hello!");
</script>

</body>
</html>
The line:
alert("Hello!");
is calling (triggering) the alert function that is built into JavaScript. We are passing (sending) the text Hello! to the alert function.
Tax Accountant Analogy
Here's an analogy to help functions make sense.

Let's pretend you hate doing taxes, and you hire an accountant to file your taxes for you.  You don't want to worry about all of the little things the accountant must do to complete your taxes; you just want to give your information to the accountant and have it done.

This is why functions are written. There are common tasks we must do often, so we write functions to help us complete those otherwise tedious or complex tasks in a simple way.

Let's write a function for our tax analogy:
function DoMyTaxes(income) {
    return income * .15;
}
alert(DoMyTaxes(60000));
The name of our function is DoMyTaxes, and our parameter (what we hand over to the accountant) is our income (a number). A parameter is a variable created to help pass a value into the function. The braces, { and } simply mark the beginning and end of the function.

If we pretend that the accountant simply calculates what we owe to be 15% of our income, and returns that value to us, we could call the function above as follows:
and we will see:
The Return Value
So above, the return statement is used to pass a value back to the caller of the function. Going back to our tax analogy, the caller would be you, calling your accountant to have them do your taxes, and the return value would be the number the tax accountant gives to you, to indicate what you owe.
Examples of Functions
Was this helpful?

Comments

Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License