What is a Function?
Function is a way to create reusable code that performs specific tasks and can be kept and maintained separately from main program.
Below is a very simple JavaScript program that shows why a function is needed in a program.
let num1, num2, sum;
num1 = 5;
num2 = 4;
sum = num1 + num2;
console.log(sum); // 9
In the code above we are performing addition operation, we start by declaring our variables num1
, num2
, sum
using the let
keyword and then assigning values for num1
, num2
and summing the values of num1
and num2
in the sum
variable.
If we want to write a program to perform substraction operation we will need to write similar program again but make few changes here and there.
num1 = 5;
num2 = 4;
let subtract = num1 - num2;
console.log(subtract);
In the code above we declared a variable called substract
and subtract num2
from num1
and then output the result using console.log
method, you can see how we are repeating ourselves for the two programs written, this is where function comes into play, we will only define a function once and call it for different cases of addition and substraction.
Below is the syntax for defining a function
function nameOfFunction(parameter1, parameter2){
// code to be executed here
}
In the syntax above we defined a function by using the keyword function
and most importantly give the function a name nameOfFunction
for example, and pass parameters (names listed in function definition) to the function, inside the curly brace is the code to be executed when the function is being called. Let us create a function that will perform substraction and addition operation.
We define the functon like so
function arithematicOperations(num1, num2, sign){
if( sign == "+"){
console.log(num1 + num2);
}else if(sign == "-"){
console.log(num1 - num2);
}
}
The Function arithematicOperations
takes three parameters num1
, num2
, sign
, where num1
and num2
will take integers as values and sign
will take a string of the arithematic operators ("+", "-") we use the if
conditional statement to check if the sign is the same as "+" and then perform addition operation or if the sign is the same as "-" and perform substraction operation.
Defining a Function will not make the Function to run, if you want the Function to run you need to call it.
We call the Function to perform addition operation
arithematicOperations(10, 5, "+"); // 15
We call the Function again to perform substraction
arithematicOperations(20, 13, "-"); // 7
You can see how we use a Function to write a code that can be reused, when writing a code and you realize that you are repeating yourself think of how you can make the code a Function. More so, if we want to make a change to the Function, we only make the change in one place (where the function is defined) and it will reflect in places where we call the function. Our code becomes more cleaner when we use Function.
Rules for creating a Function
- You declare a function with the key word function
- A Function name can start with a letter or underscore (not a number)
- A Function name should not contain spaces
- Give a function a name that reflects what it does.
- Functions names are case-sensitive (arithematicOperations and arithematicoperations are not the same)
Types of Function in JavaScript
- Function declaration
- Annonymous Function
- Immediately-invoked Function Expression (IIFE) also known as Self Invoked Function
- Arrow Function
- Callback Function
1. Function Declaration
We have seen this type of Function already in our previous examples, the previous example was not so beginner friendly, this time around we will take the examples little by little.
Function with no Parameter
We can define a function without listing paramters to the function, these type of function are usually not flexible example
function sayHello(){
console.log("Hello People!")
}
sayHello(); // Hello People
as you can see in the above code this function will always output "Hello People"
Function with parameter
If you want your function to be much more flexible on different calls list parameters at the point of defining the Function
function person(name, age, color){
console.log(`My name is ${name}, I am ${age}years old and ${color} in complexion`);
}
person("John Doe", 25, "Fair"); //My name is John Doe, I am 25years old and Fair in complexion
person("Harry Porter", 30, "Dark"); //My name is Harry Porter, I am 30years old and Dark in complexion
As you can see in the above code, we only define the Function once and pass the necessary arguments to different Function calls.
Difference between parameters and argument
Function parameters are the names listed in the function's definition while Function arguments are the real values passed to the function when you call it.
Functions with a Constant
Let's say we want to create a function that will output the perimeter of a rectangle given the formular below
perimeter = 2(length + width)
When creating a Function for the formular above, what most beginners do is to list a parameter that will hold the constant "2" at the point of defining a Function. Example
function perimeterOfArectangle(constant, length, width){
let perimeter = constant * (length + width);
console.log(perimeter);
}
perimeterOfArectangle(2, 200, 100); // 600
perimeterOfArectangle(2, 400, 200); // 1200
In the code above you can clearly see no need for listing a parameter for holding the constant "2", since "2" will always be the same when you call the function several times for different arguments.
The code can be rewritten like so
function perimeterOfArectangle(length, width){
let perimeter = 2 * (length + width);
console.log(perimeter);
}
perimeterOfArectangle(200, 100); //600
perimeterOfArectangle(400, 200); //1200
Function with a default value
In some cases you may want a function to take a default value, when you call it
function myOffice(name, color="Yellow"){
console.log(`The name of my office is ${name} and the color is ${color}`);
}
Let us call the function
myOffice("MTN"); // The name of my office is MTN and the color is Yellow
myOffice("Glo", "Green"); // The name of my office is Glo and the color is Green
In the first function call in the above examples, we did not have to pass "Yellow" as an argument in the first call since we made it a default value at the point of defining the function. in the second call, we now overide the value "Yellow" by passing "Green" as the second argument.
It is important to note that default values should always be at the right when defining a function, while required values be at the left, failure to follow the order will output undefined value for default values.
More example
function arithematicOperations(num1, num2, sign="+"){
if( sign == "+"){
console.log(num1 + num2);
}else if(sign == "-"){
console.log(num1 - num2);
}
}
arithematicOperations(5, 4); // 9
arithematicOperations(5, 4, "-"); // 1
In the first call we didn't have to pass the "+"
sign when calling the function since it has "+"
as the default value. For the second call we overide the "+"
default value with the "-"
sign
Function that returns a value
If you do not want to output the value of a function outrightly as seen in all the examples so far you can use the return statement to return the value back so you can use it in subsequent programs.
For example
function addition(num1, num2){
let sum = num1 + num2;
return sum;
}
Calling the Function
addition(3, 2);
Calling the function in the above example does not output anything on the console as we saw in previous examples, this function is returning the value back to us to we can use it in subsequent programs
For Example
if(addition(3,2) == 5){
console.log("This is a good example"); //This is a good example
}
If we want to output the value, we can assign the function to a variable and output the value of the variable or console.log
the function outrightly.
For Example
let add = addition(3,2);
console.log(add); // 5
Or this
console.log(addition(3,2)); // 5
2. Anonymous Function
This is a function with no name, and we assign this function as a value to a variable.
For Example
const greeting = function(){
console.log("Hello People"); // Hello People
}
greeting();
More Example
const addition = function(num1, num2){
let sum = num1 + num2;
return sum;
}
console.log(addition(5, 4)); // 9
The use case of this function is when we pass it as an argument in another function, example the setInterval
setInterval(function(){
console.log("My function goes here")
}, 2000)
The setInterval took two arguments, an Anonymous Function and the time in miliseconds the code will
execute.
The code above will always output "My function goes here" every 2seconds.
3. Immediately-invoked Function Expression (IIFE)
As the name implies, this type of function will run without you calling it. It is also important to mention that this type of function is also an Anonymous Function.
(function(){
console.log("Immediately invoked function"); // Immediately invoked function
})();
4. Arrow Function
Arrow Function is an alternative way of writing functions in JavaScript, this type of Function was introduced in ES6. Arrow Functions are shorthand version of the regular Function. This type of Function is mostly used by JavaScript Developers. It is important to master this Function as it is very common in frameworks like React and NodeJs.
One Line Arrow Function
const addition = (num1, num2)=> num1 + num2;
console.log(addition(10, 5)); // 15
Another example of one line Arrow Function
const greetings = ()=>"Hello World!";
console.log(greetings()); // Hello World
Arrow function without Parentheses
This type of function is very common in React and it will be a good idea to take a closer look at it.
const sayHi = val => `Hi ${val}`;
console.log(sayHi("People")); //Hi People
Multiline Arrow Function
const perimeterOfRectangle = (length, width)=>{
let perimeter = 2 * (length + width);
return perimeter;
}
console.log(perimeterOfRectangle(200, 100));
Anonymous function with Arrow Function
()=>{
console.log("Anonymous function with Arrow Function"); //Anonymous function with Arrow Function
}
Immediately-invoked Function Expression (IIFE)
We can use arrow function in IIFE
(
()=>{
console.log("Arrow function with self invoked function");
}
)();
//Arrow function with self invoked function
5. Callback Function
A callback function is a function passed as an argument to another function. Let's use Arrow Function to illustrate Callback Function.
Defining the Functions
const showResult = (result)=>{
return `Some result here ${result}`;
}
const addition = (num1, num2, myCallback)=>{
let sum = num1 + num2;
console.log(myCallback(sum));
}
Calling the Functions
addition(3, 2, showResult);
In the example above we defined two functions showResult
and addition, when calling the addition Function we now pass showResult
Function as an argument to addition Function. showResult
is a Callback Function
Using Anonymous Function as a Callback Function in setInterval
Using Anonymous Function as a Callback Function in setInterval we've seen this example before, is important we mention that the Anonymous Function in the setInterval
is a Callback Function since it is passed as an argument to the setInterval.
setInterval(()=>{
console.log("This is a callback function");
}, 2000);
This can be shorthanded like so
setInterval(()=> console.log("This is a callback function"), 2000);
Comments (2)
-
Nice article
-
Cool read
Leave a Reply
Your email address will not be published. Required fields are marked *