A JavaScript function is a block of code that performs a specific task and runs only when it is called (invoked). Functions help make code organized, reusable, and efficient. JavaScript provides multiple ways to define functions, such as function declarations, function expressions, and arrow functions. Each method has its own syntax and use case, allowing developers to write clean and efficient code.
Below are the ways of writing functions in JavaScript:
Table of Content
- Function Declaration
- Function Expression
- Arrow Functions
- Key Differences: Function Declaration vs. Function Expression
1. Function Declaration
A Function Declaration is a common way to define a function using the function keyword, followed by a name and optional parameters. It is hoisted, meaning it can be called before its definition.
Example: Below is an example that illustrates the use of Function Declaration.
// Function declaration
function add(a, b) {
console.log(a + b);
}
// Calling a function
add(2, 3);Output:
5After defining a function, we call it whenever the function is required.
2. Function Expression
Function Expression is another way to define a function. Here, the function is defined inside a variable, and the function’s value (its returned value) is stored in that variable.
Example: Below is an example that illustrates the use of Function Expression.
// Function Expression
const add = function (a, b) {
console.log(a + b);
}
// Calling function
add(2, 3);Output:
5Here, the whole function is an expression, and the returned value is stored in the variable. We use the variable name to call the function.
3. Arrow Functions
Arrow Functions were introduced in ES6 (a newer version of JavaScript). They provide a shorter syntax for writing functions. Instead of using the function keyword, you use an arrow (=>).
Example: Below is an example that illustrates the use of the Arrow Function.
// Single line of code
let add = (a, b) => a + b;
console.log(add(3, 2));Output:
5This shortens the code to a single line compared to other approaches. In a single line of code, the function returns implicitly.
Note: When a function has multiple lines of code, we use curly brackets to enclose them. If the function needs to return a value, we must use the return statement explicitly inside the brackets.
Example: This is an example with multiple lines of code in an arrow function.
// Multiple lines of code
const great = (a, b) => {
if (a > b)
return "a is greater";
else
return "b is greater";
};
console.log(great(3, 5));Output:
b is greaterKey Differences: Function Declaration vs. Function Expression
- Function Declaration: The function is defined and can be called anywhere in the code (even before it’s defined, due to something called “hoisting”).
- Function Expression: The function is defined as part of an expression (usually assigned to a variable), and it can only be called after the line where it’s defined.