Hi everyone, My name is Arinze Calistus. The purpose of this blog is to teach you all you need to know about JavaScript Functions.
JavaScript Functions
Functions are one of the fundamental building blocks of Javascript. A function is a JS method that sets a set of statements that perform a task or produces a value. It is executed when it is invoked(called) by something.
Function Definition
A JS function is defined or declared using the function
keyword, followed by:
- The name of the function.
- A list of parameters(optional) enclosed in parentheses
( )
. Multiple parameters are separated by commas(,)
. - The block of codes or the statements enclosed in curly braces
{ }
.
Here is the syntax:
function functionName(parameter1, parameter2, parameter3) {
// codes or statements to be executed
}
Parameters act as placeholder variables inside the function. When the function is called, the variables are assigned to the arguments (value) provided when the function is called.
// defining functions
function writeText(str) {
document.getElementById("demo").innerHTML = str;
}
// calling a function
writeText("Hello World!");
Calling a Function
Fuctions will only be executed when they are called or invoked. A function can be called inside a JS program. A function can be called when an event happens, most commonly when a button is clicked.
function addNumbers(num1, num2) {
var sum = num1 + num2;
document.getElementById("demo").innerHTML = sum;
}
<p id="demo"> Sum will be printed here. </p>
<button onclick="addNumbers(2, 5)"> Add </button>
Please be reminded that functions don't require parameters. The function's task below shows a dialog box with no parameters.
function showDialog( ) {
alert("Hello World!");
}
Why Use Functions?
Functions in JS are just like tools in real life, they make coding easier. Instead of writing a block of codes over and over again, we can just re-use the same code many times.
Thanks for reading!!