DEV Community

Abhay Yt
Abhay Yt

Posted on

Comprehensive Guide to Functions in JavaScript

Functions in JavaScript

Here’s a comprehensive guide to Functions in JavaScript with examples:


1. What is a Function?

A function is a block of reusable code designed to perform a particular task. It is executed when it is invoked or called.

Syntax:

function functionName(parameters) {
  // Code to execute
}
Enter fullscreen mode Exit fullscreen mode

Example:

function greet(name) {
  console.log(`Hello, ${name}!`);
}
greet("Alice"); // Output: Hello, Alice!
Enter fullscreen mode Exit fullscreen mode

2. Types of Functions in JavaScript

A. Function Declaration

A function declared using the function keyword.

Example:

function add(a, b) {
  return a + b;
}
console.log(add(2, 3)); // Output: 5
Enter fullscreen mode Exit fullscreen mode

B. Function Expression

Functions can also be stored in variables.

Example:

const multiply = function (a, b) {
  return a * b;
};
console.log(multiply(2, 3)); // Output: 6
Enter fullscreen mode Exit fullscreen mode

C. Arrow Functions (ES6)

A concise syntax for writing functions.

Syntax:

const functionName = (parameters) => {
  // Code to execute
};
Enter fullscreen mode Exit fullscreen mode

Example:

const subtract = (a, b) => a - b;
console.log(subtract(5, 3)); // Output: 2
Enter fullscreen mode Exit fullscreen mode

D. Anonymous Functions

Functions without a name, often used as callbacks.

Example:

setTimeout(function () {
  console.log("This runs after 2 seconds");
}, 2000);
Enter fullscreen mode Exit fullscreen mode

E. Immediately Invoked Function Expression (IIFE)

A function that runs immediately after it is defined.

Example:

(function () {
  console.log("IIFE is executed immediately!");
})();
Enter fullscreen mode Exit fullscreen mode

3. Parameters and Arguments

  • Parameters: Variables defined in the function definition.
  • Arguments: Values passed when calling the function.

Example:

function greet(name, age) {
  console.log(`Hi ${name}, you are ${age} years old.`);
}
greet("Bob", 25); // Output: Hi Bob, you are 25 years old.
Enter fullscreen mode Exit fullscreen mode

4. Default Parameters

Provide default values for parameters if no argument is passed.

Example:

function sayHello(name = "Guest") {
  console.log(`Hello, ${name}!`);
}
sayHello(); // Output: Hello, Guest!
Enter fullscreen mode Exit fullscreen mode

5. Rest Parameters

Used to handle an indefinite number of arguments as an array.

Example:

function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
Enter fullscreen mode Exit fullscreen mode

6. Return Statement

Functions can return a value using the return statement.

Example:

function square(num) {
  return num * num;
}
console.log(square(4)); // Output: 16
Enter fullscreen mode Exit fullscreen mode

7. Callback Functions

A function passed as an argument to another function and executed later.

Example:

function processUserInput(callback) {
  const name = "Charlie";
  callback(name);
}
processUserInput((name) => {
  console.log(`Hello, ${name}!`);
});
// Output: Hello, Charlie!
Enter fullscreen mode Exit fullscreen mode

8. Higher-Order Functions

Functions that accept other functions as arguments or return functions.

Example:

function applyOperation(a, b, operation) {
  return operation(a, b);
}

const add = (x, y) => x + y;
const multiply = (x, y) => x * y;

console.log(applyOperation(3, 4, add)); // Output: 7
console.log(applyOperation(3, 4, multiply)); // Output: 12
Enter fullscreen mode Exit fullscreen mode

9. Closures

A closure is a function that remembers its outer variables even after the outer function has finished executing.

Example:

function outerFunction(outerVariable) {
  return function innerFunction(innerVariable) {
    console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
  };
}
const myFunction = outerFunction("Outside");
myFunction("Inside");
// Output: Outer: Outside, Inner: Inside
Enter fullscreen mode Exit fullscreen mode

10. Function Scope

Functions have their own local scope.

Example:

function showMessage() {
  let message = "Hello, World!";
  console.log(message);
}
showMessage();
// console.log(message); // Error: message is not defined
Enter fullscreen mode Exit fullscreen mode

11. Recursion

A function that calls itself.

Example:

function factorial(n) {
  if (n === 1) return 1;
  return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120
Enter fullscreen mode Exit fullscreen mode

12. Pure Functions

A pure function produces the same output for the same input and has no side effects.

Example:

function add(a, b) {
  return a + b;
}
console.log(add(2, 3)); // Output: 5
Enter fullscreen mode Exit fullscreen mode

Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.

Top comments (0)