Function In JavaScript
In this tutorial, you will learn about javascript functions, how to define them, how to use them, why to use them, etc with various examples.
What is a function?
A function is a named sequence of statements that performs a specific operation. Functions are used to break down a program into smaller, reusable pieces.
function name(param1, param2, ...) {
// statements
}
In javascript, a function is defined using the keyword function
and is immediately followed by the function name and a pair of parenthesis.
Inside the parenthesis, you can define any number of arguments that are passed to the function when it is called.
The function can return a value by using the return statement, or it can end the function by using the return
keyword.
The basic idea of a function is to reduce the number of repeated code blocks and executing a code block whenever needed.
Example
function add(a, b) {
let sum = a + b; // statement
return sum; // return
}
console.log(add(1, 2));
Javascript Function Declaration
A function declaration is a way to declare a function in javascript. It is a way to tell javascript that you want to create a function and to give it a name.
To use a function you must first declare it. In javascript, the function is declared by using the function
keyword.
Syntax
function name_of_function (param1, param2,...) {
// javascript statements
return something;
}
Here are the steps to declare a function in javascript.
- Start function with the
function
keyword - Then write the name of the function with a space. The naming convention of function is the same as a variable naming convention.
- Then give arguments to the function enclosed in parentheses and separated by commas like (parameter1, parameter2, ...)
- Then define the function body by curly braces {...}
- At the end of the function use
return
keyword to return any object or value.
Example
// Function declaration
function hello() {
console.log("Hello World!");
}
Try It
Javascript function call
Just defining a function does nothing until it is invoked or called.
How to call a function in javascript?
To call a function, you need to use the function name followed by a parenthesis and the arguments that you want to pass to the function.
If there is no parameter then write blank parenthesis.
Example 1:
Example
// Function declaration
function hello() {
console.log("Hello World!");
}
// Function call
hello();
Try It
Example 2:
Example
// Function declaration
function hello(name) {
console.log(`Hello ${name}!`);
}
// Function call
hello("John");
Call Javascript Function From HTML
You can call a javascript function from HTML using events.
When an event occurs like button click, mouse move, document load, etc then you can use some event handler to trigger the event which will call the function.
Example:
Example
<!-- function called when page load -->
<body onload="message()">
<h2>Use some event to call a function from HTML.</h2>
<!-- function called when button clicked -->
<button onclick="my_function()">Click</button>
<script>
function message() {
alert("function executed!");
}
</script>
</body>
Try It
Note: You can call a function from any event we want and as many times.
Javascript function parameter
Javascript function parameters are the values that are passed in the function to be used inside its statements.
The actual values that are passed in the function are known as arguments while the variable that is declared in the function is known as a parameter.
The data type of javascript function parameter could be any valid data type, for example, string, number, array, etc.
Example
function message(user, message) {
console.log("User: " + user + " , Message: " + message);
}
message("Herry", "How are you?");
message("John", "I'm fine.");
Try It
What happens when you provide more or fewer parameters to the function than the defined arguments?
- When a number of arguments are less than parameters then the rest parameters will be undefined
- when the number of arguments are more than parameters then extra arguments will be ignored
Let's see an example to understand.
Example
function fullName(firstname, lastname) {
console.log(firstname + " " + lastname);
}
fullName("Stephen", "Hawking"); // Stephen Hawking
fullName("Stephen", "William", "Hawking"); // Stephen William
fullName("Stephen"); // Stephen undefined
Try It
Javascript Function Return
Javascript function can return values to the caller. The return value is known as return value.
To return something from the function return
keyword is used with the return value separated by space.
The function stops execution when reached to return
statement even if there are more statements in the function after a return.
The return value can be stored in a variable.
Example
function multiply(a, b) {
return a * b;
}
// storing return value in a variable
var value = multiply(4, 6);
console.log(value);
Try It
The return
value can be placed anywhere in the function but as soon as the function finds a return statement it stops further execution of the code in a function.
Also, you can use a return
statement without returning any value just to stop the execution of the function.
Example
function pass(mark) {
if (!mark) {
console.log("Invalid Marks!");
return;
}
if (mark > 40) {
console.log("Pass!");
return true;
}
else {
console.log("Fail!");
return false;
}
}
pass(60);
Try It
Javascript Function Local Variable
The variables that are defined inside the function have local scope. This means these variables can't be accessed outside the function.
But a function can access the variable that is defined outside the function.
Example
function localVariable() {
// local scope
let a = 10;
console.log("'a' inside function is " + a);
}
localVariable();
console.log("'a' outside function is " + typeof a);
Try It
Javascript Function Expression
Function expression lets us define the function and assign it to some variable.
A function expression, in general, has no name hence it is also called an anonymous function.
A function expression is more convenient to pass as an argument in callback functions.
Example
var sum = function (num1, num2) {
return num1 + num2;
}
// function called using variable name
console.log(sum(12, 32));
Try It
Javascript Function Declaration VS Expression
These are 2 important differences between function declaration and function expression:
-
A function declaration can be hoisted but a function expression can't be hoisted. It means you can use a function before it is declared while you can't use a function before function expression is declared.
hello(); // run successfully function hello() { // function declaration return "Hello World!"; }
hello(); // error function not declared let hello = function() { // function expression return "Hello World!"; }
-
A function declaration is loaded before execution of any code but function expression loads only when the interpreter reached that line of code.
Javascript Immediately Invoked Function Expression(IIFE)
immediately Invoked Function Expression (IIFE) is the function is executed right after the function is declared.
Syntax of IIFE
(function () {
// statements;
})();
The variables defined inside IIFE is not accessible outside the function.
Example
(function(){
console.log("Function executed immediately after it is declared.")
})();
Try It
If you assign IIFE to some variable then it stored the function's return value, not the function itself.
Example
var example = (function(){
return "Returned value is stored."
})();
console.log(example);
Try It
Frequently Asked Questions
-
What is function and method in JavaScript?
A function is a block of code that is used to perform a specific task. A method is a function that is associated with a specific object. A method can also be an instance function, which means that it is associated with an object and can be called directly on that object.
Points to remember:
- Function in javascript is declared using the
function
keyword. - A function can have any number of arguments starting from 0.
- You can call the javascript function from HTML using some event.
- As soon as the function reaches the return statement it stops further execution of it.
- Variable defined in a function has local scope and can't be accessed outside the function.