Sonu Kumar
2 min readJan 30, 2024

What are different ways of creating functions in JavaScript?

In JavaScript, a function is a reusable block of code designed to perform a specific task or return a value. Functions help modularize code, making it more organized and easier to maintain. There are several ways to create functions in JavaScript. Here are three common ways:

1. //**Function Declaration:**
//— Syntax:

function functionName(parameters) {
// code to be executed
}

//— Example:

function greet(name) {
console.log(“Hello, “ + name + “!”);
}
greet(“John”);

//— Real-time example: A function that calculates the area of a rectangle.

function calculateArea(length, width) {
return length * width;
}
console.log(“Area: “ + calculateArea(5, 10)); // Output: Area: 50
2. //**Function Expression:**
//— Syntax:

const functionName = function(parameters) {
// code to be executed
};

//— Example:

const greet = function(name) {
console.log(“Hello, “ + name + “!”);
};
greet(“Jane”);

// — Real-time example: A function expression to check if a number is even.

const isEven = function(num) {
return num % 2 === 0;
};
console.log(isEven(6)); // Output: true
3. //**Arrow Function (ES6):**

const functionName = (parameters) => {
// code to be executed
};

//— Example:

const greet = (name) => {
console.log(“Hello, “ + name + “!”);
};
greet(“Alice”);

//— Real-time example: An arrow function for adding two numbers.

const add = (a, b) => a + b;
console.log(add(3, 7)); // Output: 10

These examples showcase the flexibility of JavaScript functions, whether declared traditionally, as expressions, or using arrow functions. They can be adapted to various scenarios, offering modularity and reusability in your code.
#javascript #function #arrowfunction #nodejs #es6

Please follow me for more details:
https://medium.com/@me.sonu300

Sonu Kumar

Full stack Web developer with experience and I love reading article such blogs books and writing.