Need of Functions
You have visited the Amazon site and bought a product. And you have seen the Add to Cart button on each item.
Do we need to write different code for each Add to Cart button? NO.
If we write different code for each button is very bad idea. This is where the concept of a function comes in. We can simply write a function called ‘AddToCart’ that will add the product to the cart, and we can just call it for every product. There is no need to write the same code again.
What is a Function?
In JavaScript, a function is a reusable block of code that can be defined and then executed whenever needed. Functions are one of the fundamental building blocks of JavaScript and play a crucial role in structuring and organizing code.
Example:-
// Guess the Output
function fn(){
console.log("Hello");
}
JavaScriptWhat will be the output of above Code?
Nothing it will not Print Anything. Why? because we have not called or invoked this function. Let’s see how to do this.
function fn(){
console.log("Hello");
}
fn(); // Invoked the function
JavaScriptOutput:-
Hello
JavaScriptTypes of Function in JavaScript
Function Statement in JavaScript
- The function statement declares a function. A declared function is “saved for later use”, and will be executed later when it is invoked (called).
Example:-
function javascript(){
console.log("Welcome to JS")
}
javascript();
//output will be Welcome to JS
JavaScriptAnonymous function in JavaScript
- A function without a name is called anonymous function
- Anonymous functions are used as values , i.e. you can use it to assign it to some variables as well.
Example:
let add = function (x, y) {
return x + y;
};
let result = add(5, 3);
console.log(result); // Output: 8
JavaScriptHigher Order Function(HOF) in JavaScript
A Higher-Order Function is a regular function that takes one or more functions as arguments and/or returns a function as a value from it.
Here is an example of a function that takes a function as an argument.
// Define a function that takes a function as an argument.
function getCapture(camera) {
// Invoke the passed function
camera();
}
// Invoke the function by passing a function as an argument
getCapture(function(){
console.log('Canon');
});
JavaScriptNow let us take another function that returns a function.
// Define a function that returns a function
function returnFunc() {
return function() {
console.log('Hi');
}
}
// Take the returned function in a variable.
const fn = returnFunc();
// Now invoke the returned function.
fn(); // logs 'Hi' in the console
// Alternatively - A bit odd syntax but good to know
returnFunc()(); // logs 'Hi' in the console
JavaScriptBoth of the examples above are examples of Higher-Order functions. The functions getCapture() and returnFunc() are Higher-Order functions. They either accept a function as an argument or return a function.
Please note, it is not mandatory for a Higher-Order function
to perform both accepting an argument and returning a function. Performing either will make the function a Higher-Order function.A function which takes another function as an argument or returns a function is known as a higher order function.
The Benefits of Higher-Order Functions
function calculate(operation, initialValue, numbers) {
let total = initialValue;
for (const number of numbers) {
total = operation(total, number);
}
return total;
}
function sum(n1, n2) {
return n1 + n2;
}
function multiply(n1, n2) {
return n1 * n2;
}
calculate(sum, 0, [1, 2, 4]); // => 7
calculate(multiply, 1, [1, 2, 4]); // => 8
JavaScriptWhat’s great is you can reuse the calculate()
function to support multiple operations by providing different operation functions: addition, multiplication, and more.
Additionally, the concept of the higher-order function allows composability of functions. For example, you compose calculate()
with sum()
to calculate the sum of all numbers in an array. If you want to calculate the production, then you compose calculate()
and multiply()
.
The composability of functions thanks to higher-order functions is an important instrument in functional programming.
The higher-order functions help reduce the code duplication and favor the single-responsibility principle.
Arrow Functions
Recently, the ES6 version of JavaScript has introduced the arrow function. And, characterized as “=>
” (looks like an arrow to me!). Moreover, it gives us the ability to have a shorter syntax. Therefore, it behaves like the function expression but looks different because of the arrow operator.
Here are the things needed to remember about arrow functions:
- It consists of zero or more parameters that surround within an open and close parenthesis also known as round brackets ().
- It is followed by the => operator
- After the arrow operator, it followed by a function body. Just remember, the body only needs to be enclosed by curly braces {} if there’s more than one expression. Therefore you can omit the curly braces if there’s only one expression.
See the snippet below.
//declarative function
function showFavoriteLanguage(language) {
return `I love ${language}`;
}
//arrow function equivalent
let showFavoriteLanguage= (language) => `I love ${language}`;
JavaScriptIn this section, let’s convert a function declaration into an arrow function. First, let’s define a function.
function getProductOfTwoNumbers(num1, num2) {
return num1 * num2;
}
JavaScriptSecond, convert it into an arrow function.
let getProductOfTwoNumbers = (num1, num2) => {
return num1 * num2;
}
JavaScriptLooks like a function expression. Right? Want some style? We can remove the curly braces.
let getProuductOfTwoNumbers = (num1, num2) => num1 * num2;
JavaScriptGreat! Looks good to me.
If you are curious, what if we only have one parameter? Let us see an example below.
//gets the first element in the passed array
const getFirstElement = (arr) => arr[0];
//squares the passed number
const squareNum = (num) => Math.pow(num, 2);
JavaScriptIIFE Functions
You might be familiar with functions in JavaScript. An IIFE (Immediately Invoked Function Expression) is a special type of function which is invoked implicitly.
Even if you don’t invoke or call it in your code, it will run on it’s own. You can relate it with a callback function which is automatically called when a particular event is fired.
Syntax:
(function () {
console.log('IIFE')
})()
JavaScriptYou can also define an arrow function as an IIFE.
(() => {
console.log('IIFE')
})()
JavaScriptThe Benefits of IIFE Functions
You might be wondering, well what’s the use of this type of function? This same thing can be done like this:
function func(){
console.log('IIFE')
}
func()
JavaScriptWell, here’s the catch. When we define a global variable in JavaScript, it can be accessed from anywhere in our code. For example,
var b = 10
function print(){
b = 8
console.log(b) // output: 8
}
print()
console.log(b) // output: 8
JavaScriptIn the above code, the value of the variable b
is modified from 10
to 8
. But what if we don’t want to modify the value of the global variable . What can we do?
One thing we can do is to initialize a new variable b
inside the scope of the function print()
just like this:
var b = 10
function print(){
let b = 8
console.log(b) // output: 8
}
print()
console.log(b) // output: 10
JavaScriptWe were able to create a new variable inside the scope of the function without actually modifying the actual global variable.
But, there’s another way! Let’s say you don’t want to reuse the function print()
and also you don’t want to create a mess with global variables unintentionally. In that case, you can use an IIFE. Here’s how you can do that :
var a = 8;
((a) => {
a = 9; // modifying the copy of 'a'
console.log(a); // output: 9
})(a) // passing a copy of variable as an argument
console.log(a) // output: 8
JavaScriptIn the above example, we are passing the value of variable a
to the IIFE. Remember that we are only passing a copy of the variable, so we are not actually modifying the global variable.
This is most useful when you are dealing with multiple files which are being imported and exported in your project and you don’t know the name of every global variable defined.
Conclusion
Functions in JavaScript are versatile tools that enhance the language’s flexibility, allowing developers to write cleaner, more organized, and reusable code. From simple utility functions to complex higher-order functions, understanding and leveraging functions is fundamental to effective JavaScript programming. Whether it’s managing application logic, handling events, or creating dynamic web features, functions serve as the building blocks that enable developers to implement sophisticated behaviors in a structured and maintainable way.
Frequently Asked Questions
Ans: A JavaScript function is a reusable block of code designed to perform a particular task. Functions are fundamental building blocks in JavaScript, allowing code to be called multiple times without repetition.
Q2. Why are functions important in JavaScript?
Ans: Functions are crucial because they enable code reusability, improve readability, and make maintenance easier. They allow for the encapsulation of code logic that can be executed whenever needed.
Q3. How do you define a function in JavaScript?
Ans: A function can be defined using the function
keyword followed by a name, parentheses ()
containing any parameters, and curly braces {}
containing the code block to execute.
Q4. What is an anonymous function?
Ans: An anonymous function is a function without a name. These functions can be assigned to variables or used as arguments to other functions. They are often used in situations where a function is needed temporarily or for a single use.
Q5. What is a higher-order function (HOF)?
Ans: A higher-order function is a function that either takes one or more functions as arguments or returns a function as its result. HOFs are a core aspect of functional programming in JavaScript.