Intro to Custom JavaScript Functions
Learn how to write your own functions in this tutorial provided by EasyProgramming.net
by Nazmus Nasir
HTML
<!-- Easy JavaScript # 27 - Custom JavaScript Functions -->
<p>
Welcome to the 27th Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. This tutorial will give you the knowledge you need to create your own custom functions.
</p>
<p>
A function is just a block of code designed to perform a particular task. Functions are also reusable and can be invoked multiple times within the same script (or even from external scripts if a reference to the function definition exists).
</p>
<p>
Functions can be tied to buttons and be used as methods in objects. They are delcared with the JavaScript reserved keyword named <code>function</code> followed by the name of the function. They can also be assigned to variables. And functions can either return values or just do a basic command and end.
</p>
<p>
Parameters can be defined to receive values from another part of your script. The piece of code sending the parameter is called the argument.
</p>
<h2>
Syntax of a function:</h2>
<p>
<code><pre>
function nameOfFunction(parameter1, parameter2...){
//declare local variables
//do something with parameter 1
//do something with parameter 2
//do other things
//return value (optional)
}</pre>
</code>
</p>
<h2>
Invoking a function
</h2>
<code>
<pre>nameOfFunction(argument1, argument2...);</pre>
</code>
<p>
<h2>
Let's practice:</h2>
You borrowed $100 with an interest rate of 5%.<br />
The total owed with interest is: $<span id="total">___</span>
<br /><br />
<!-- You also borrowed $500.<br />
The total owed with interest is: <span id="2nd">___</span>
</p> -->
JavaScript
var loan = 100;
var interest = 0.05;
//var addInterest = function(x,y){
// var calculated = x + (x * y);
// console.log(calculated);
//}
addInterest(loan,interest);
addInterest(5,1.00);
addInterest(25,0.50);
addInterest(500,0.06);
function addInterest(x,y){
var calculated = x + (x * y);
document.getElementById("total").innerHTML = calculated;
console.log(calculated);
}