DEV Community

Lokesh
Lokesh

Posted on

Types of Functions in JavaScript

What Is a Function?

A function is a reusable block of code that performs a particular task.

Instead of writing the same code again and again, we can create a function and call it whenever we need it.

JavaScript has different ways to create and use functions. Let's understand some common types with simple examples.

1. Function Declaration

A function declaration is a common way to create a function using the function keyword.

function greet() {
    console.log("Hello World!");
}

greet();
Enter fullscreen mode Exit fullscreen mode

Output:

Hello World!
Enter fullscreen mode Exit fullscreen mode

Here, we create a function named greet and call it to execute the code inside it.

2. Function with Parameters

Parameters allow us to pass information into a function.

function greet(name) {
    console.log("Hello " + name);
}

greet("John");
Enter fullscreen mode Exit fullscreen mode

Output:

Hello John
Enter fullscreen mode Exit fullscreen mode

Here, name is a parameter, and "John" is the argument passed to the function.

3. Function with a Return Value

The return statement sends a result back to the place where the function was called.

function add(a, b) {
    return a + b;
}

let result = add(10, 20);
console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output:

30
Enter fullscreen mode Exit fullscreen mode

This is useful when we want to calculate a value and use it somewhere else in our program.

4. Function Expression

A function expression is created by assigning a function to a variable.

const greet = function() {
    console.log("Welcome!");
};

greet();
Enter fullscreen mode Exit fullscreen mode

Output:

Welcome!
Enter fullscreen mode Exit fullscreen mode

Unlike a function declaration, this function expression cannot be called before the variable is initialized.

5. Arrow Function

Arrow functions provide a shorter way to write functions.

const add = (a, b) => {
    return a + b;
};

console.log(add(5, 10));
Enter fullscreen mode Exit fullscreen mode

Output:

15
Enter fullscreen mode Exit fullscreen mode

For simple functions, we can write it even shorter:

const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

Arrow functions are commonly used in modern JavaScript, especially with array methods such as map() and filter().

6. Anonymous Function

An anonymous function is a function without its own name.

setTimeout(function() {
    console.log("Hello!");
}, 1000);
Enter fullscreen mode Exit fullscreen mode

Here, the anonymous function runs after approximately one second.

Anonymous functions are often used as callbacks, where a function is passed to another function.

Why Are Functions Important?

Functions help us:

  • Reuse code.
  • Avoid repeating the same instructions.
  • Organize programs into smaller parts.
  • Perform calculations.
  • Make code easier to read and maintain.

Top comments (0)