If you are working with JavaScript, you have also heard about JavaScript functions. A function is like a block of code that you can use again and again whenever you need. In this blog, we will discuss the basics of JavaScript functions like what they are, their types, and how to use them. So let’s get started.
Table of Contents:
What are JavaScript Functions?
JavaScript functions are the reusable blocks of codes that perform a specific task. You can call them whenever you need. Functions take inputs known as ‘Parameters’ and return output known as ‘return value’.
Syntax:
function functionName(parameters) {
// Code
return value;
}
Benefits of using JavaScript Functions
JavaScript functions help you to organize your code and complete your tasks quickly. There are 2 main benefits of using JavaScript functions:
- Code reusability: You can call a function multiple times in your code depending on your need.
- Less coding: You can add functions instead of writing the whole code multiple times which makes the program look clean and organized.
JavaScript Function Declarations
Function declaration in JavaScript is a way to create a set of instructions that you can use multiple times. It is created by using the ‘function’ keyword followed by the function name, parameters, and code block.
Syntax:
function functionName(parameter1, parameter2) {
// Code
return;
}
Explanation:
- Function Parameters: Parameters are variables written inside the ‘parentheses ()’ when you declare a function. They are the placeholders for the values you want to give to the function when you call it.
- Return Statement: Return is the value that the function will return using the ‘return’ keyword. It will give you the result of the function which you can use later in code.
- Function Invocation: To execute the function, you call it by using its name followed by parentheses. If you have used parameters in the function then provide the values inside the parentheses.
JavaScript Function Declaration Example:
Let’s see a simple example of a JavaScript function declaration to find the sum of two numbers.
function add(x, y) {
return x + y; // return statement
}
let result = add(2, 3); // calling the function
console.log("Sum of x and y is " + result);
Here,
- The function ‘add’ took 2 parameters ‘x’ and ‘y’.
- The values of x and y are 2 and 3 respectively.
Output:
JavaScript Function Expressions
Function expression in JavaScript is when you create a function and store it in a variable. It is different from the function declaration because you can’t use the function before it’s created. You can create a function expression in two ways either with the name or anonymous (without the name).
Syntax:
const functionName = function(parameter1, parameter2) {
// Code
return;
};
Example:
Here we will create a function and store it in the variable ‘greet’. This function will take the ‘name’ as a parameter and will return the message when it is called.
const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet("This is Intellipaat!"));
Output:
Arrow Functions in JavaScript
Arrow functions in JavaScript are just a shorter way to write a function. It contains ‘=>’ instead of the actual function keyword. They were introduced in ES6 (ECMAScript 6) has a shorter syntax compared to regular functions.
Syntax:
const functionName = (parameters) => {
// Function body
return result;
};
Example:
Let’s create an arrow function to get the multiplication of two numbers.
const multiply = (a, b) => {
return a * b;
};
console.log(multiply(4, 7));
Output:
Pass by Value vs. Pass by Reference
In JavaScript, data can be passed to function in two ways depending on if the value is primitive or non-primitive. Let’s see that in detail:
- Pass by Value (for primitive data types): In this, you provide a copy of a variable to the function so any changes in the function won’t affect the original variable. You can only do it with data types like numbers, strings, and booleans.
- Pass by Reference (for non-primitive data types): In this, you provide the original variable to the function and not a copy so any changes in the function will affect the variable too. This happens with objects and arrays.
Anonymous Functions in JavaScript
As the name suggests, an anonymous function is a function without a name. Mostly anonymous functions are stored in variables or used as arguments in other functions.
Example:
Let’s see an example where we will store an anonymous function inside a variable ‘hello’.
const hello = function() {
console.log("Hello, Intellipaat!");
};
hello();
Output:
High-Order Functions in JavaScript
A high-order function is a function that will either take another function as an argument or return a function as a result. High-order functions allow you to make your code reusable and more flexible.
Example: In this example, the ‘greet’ function will return another function which will make it a high-order function.
function greet(name) {
return function(message) {
console.log(message + ", " + name);
};
}
const greetIntellipaat = greet("Intellipaat");
greetIntellipaat("Hello");
Output:
Self-Invoking Functions in JavaScript
Self-invoking functions in JavaScript are those functions that run immediately after they are defined. You don’t need to call them separately. You just need to write the function followed by ‘()’. It is important to put the function inside parentheses to tell that it’s a function expression.
Example: Let’s see an example of a self-invoking function in JavaScript.
(function() {
console.log("I am a self-invoking function!");
})();
Output:
Callback Functions in JavaScript
A callback function in JavaScript is a function that is passed as an argument and can be used in another function. It will be executed after that function is completed. Callback functions will help you hold your code and let other code run while waiting for the task to finish.
Example: In this example, we will create a ‘num’ function that takes a number ‘n’ and a callback function. Then we will create another ‘square’ function that is passed as a callback and will return the square of the number.
function num(n, callback) {
return callback(n);
}
const square = (n) => n * n;
console.log(num(4, square));
Output:
Nested Functions in JavaScript
A nested function is a function that is defined inside another function. The nested function can use the outer function’s variables and parameters but the outer function can’t use the inner function’s variables and parameters.
Example: Let’s see a simple example of how nested functions work.
function outerFunction(outerVariable) {
function innerFunction(innerVariable) {
console.log("Outer Variable: " + outerVariable);
console.log("Inner Variable: " + innerVariable);
}
innerFunction("Hi, this is nested function!");
}
outerFunction("Hi, this is outer function!");
Output:
Pure Functions in JavaScript
Pure functions in JavaScript are those functions that give you the same output for the same input and will not change the external state or variables. They don’t have any side effects.
Example: In this example, we will create a function ‘add’ which is a pure function and will give you the same result for the same input.
function add(a, b) {
return a + b;
}
console.log(add(4, 6));
Output:
JavaScript Function Hoisting
Hoisting is a feature of JavaScript that moves your functions to the top of the code before the code gets run. It means you can call the function before it is written in the code. Function declarations are hoisted in JavaScript but function expressions are not.
Key points:
1. If you declare a function using the ‘function’ keyword then JavaScript will move the function to the top. It will let you call the function before it appears in the code.
Example:
greet();
function greet() {
console.log("Hello, Intellipaat!");
}
Output:
2. If you assign a function to a variable using var, let, or const then this function will not be hoisted. So you can only call the function after it’s defined.
Example:
greet();
var greet = function() {
console.log("Hello, Intellipaat!");
};
Output:
Choosing the Right Function Type in JavaScript
- Function Declarations: You need to use a named function so you can use it later in the code. It is best for global functions.
- Function Expressions: It is used when you want to assign a function to a variable. It is best for callback functions.
- Arrow Functions: Arrow functions are used when you want to write shorter syntax for simple functions.
- Self-Invoking Functions: It is used when you want to run the functions as soon as they are defined. It is best for encapsulation methods.
Conclusion
So far in this blog, we have learned what JavaScript functions are, their types including arrow functions, callback functions, nested functions, etc., and how to use them. JavaScript is a programming language that will help you make your website interactive and JavaScript functions are the reusable block of codes that performs a specific task. You can call them whenever you need.
FAQs – JavaScript Functions
1. What is a JavaScript function?
JavaScript function is a reusable block of codes that performs a specific task. You can call it multiple times whenever you need.
2. What are function parameters?
Parameters are variables written inside the ‘parentheses ()’ when you declare a function. They are the placeholders for the values you want to give to the function when you call it.
3. What is the difference between function declarations and function expressions?
Function declaration in JavaScript is a way to create a set of instructions that you can use multiple times. It is created by using the ‘function’ keyword.
Function expression in JavaScript is when you create a function and store it in a variable. It is different from the function declaration because you can’t use the function before it’s created.
4. What is a callback function?
A callback function in JavaScript is a function that is passed as an argument and can be used in another function. It will be executed after that function is completed.
5. What is a self-invoking function?
Self-invoking functions are those functions that run immediately after they are defined. You don’t need to call them separately.
6. How do you call a function?
You can call a function by using its name followed by ‘parentheses ()’.