Master JavaScript Functions: Unraveling Function Closures, First-Class & Higher-Order Functions
Tags: webdev, javascript, programming, beginners
Published: 2023-05-31 12:10:18

This guide is for all coders eager to explore function closures, first-class functions, and higher-order functions in JavaScript.

**Key takeaways:**

1. Grasping the concept of first-class functions.
    
2. Learning to pass functions as arguments.
    
3. Mastering returning functions within functions.
    
4. Assigning functions to variables.
    
5. Identifying higher-order functions.
    
6. Gaining a clear understanding of function closures.
    

Let's dive into the fascinating world of JavaScript functions!

## **First-Class Functions**

First-class functions are a unique feature in JavaScript, meaning that functions here are treated like any other variable. They can be passed as arguments, returned by another function, or assigned as a value to a variable.

**Passing as an argument:**

```javascript
function print(value) {
  console.log(value);
}

function greet(name, callFun) {
  callFun("Hello " + name);
}

greet("Sammy", print); // Outputs: Hello Sammy
```

In this snippet, `print()` is passed as an argument to `greet()`, showcasing how functions can be used as arguments in JavaScript.

**Returning from another function:**

```javascript
function house() {
  return function () {
    console.log("Hello");
  };
}

house()(); // Outputs: Hello
```

In this example, `house()` returns another function, demonstrating that functions can also be returned by other functions.

**Assigning to a variable:**

```javascript
var printHello = function () {
  console.log("Hello");
};

printHello(); // Outputs: Hello
```

Here, we assign a function to the variable `printHello` and call it using the variable name followed by parentheses.

## **Higher-Order Functions**

A higher-order function is a function that either takes one or more functions as arguments or returns a function as a result. It's a crucial concept in functional programming.

**Taking a function as an argument:**

```javascript
function delay2sec(callback) {
    setTimeout(() => {
        callback('Something');
    }, 2000);
}
delay2sec(console.log); // Outputs: Something after 2 seconds
```

This example showcases a function `delay2sec()`, which takes `console.log` as an argument and executes it after a delay of 2 seconds.

**Returning a function as a result:**

```javascript
function outSide() {
    let num = 5;
    return function () {
        return num;
    };
}
```

In this case, `outSide()` returns a function that has access to its parent function's variables, demonstrating function closure.

## **Function Closures**

A closure is a function bundled with its surrounding lexical environment, granting the inner function access to the outer function's scope.

**Local Variable:**

```javascript
function starting() {
  let num = 0; // Local variable
}
```

The variable `num` here is a local variable, only existing within the `starting()` function.

**Global Variable:**

```javascript
let num = 0; // Global variable

function first() {
  console.log(num);
}

function second() {
  console.log(num);
}
```

The variable `num` is a global variable accessible to all parts of the code, including `first()` and `second()` functions.

**Function Closure:**

```javascript
function host() {
  let num = 0;
  return function () {
    num++;
    return num;
  };
}

let firstCall = host();

console.log(firstCall()); // Outputs: 1
console.log(firstCall()); // Outputs: 2
console.log(firstCall()); // Outputs: 3
```

Here, `host()` declares a local variable `num`, and its returned function has access to `num`. Each call to `firstCall()` increments `num`.

## **Wrapping Up**

We've just sailed through the world of JavaScript functions, exploring function closures, first-class functions, and higher-order functions. These concepts are essential to improving your JavaScript skills and broadening your understanding of functional programming. Happy coding!