DEV Community

Kaziu
Kaziu

Posted on

1

Closure + Arrow function = extremely short

▼ If you don't know about Closure, I've already written about it

There is this closure function

function addCountFactory(num) {
    function addCount(value) {
        return num + value;
    }
    return addCount;
}

const addOne = addCountFactory(1);
const result = addOne(10);
console.log(result); // 11
Enter fullscreen mode Exit fullscreen mode

If I change it to arrow function, it would be like this

1

const addCountFactory = num => { // ⭐ here
    function addCount(value) {
        return num + value;
    }
    return addCount;
}
Enter fullscreen mode Exit fullscreen mode

2

remove unnecessary return

const addCountFactory = num => {
    return function addCount(value) { // ⭐ here
        return num + value;
    }
    // ⭐ delete "return addCount"
}
Enter fullscreen mode Exit fullscreen mode

3

name of function is not necessary

const addCountFactory = num => {
    return function(value) { // ⭐ here
        return num + value;
    }
}
Enter fullscreen mode Exit fullscreen mode

4

just delete { } block

const addCountFactory = num => function(value) {
        return num + value;
}
Enter fullscreen mode Exit fullscreen mode

5

change to arrow function

const addCountFactory = num => value => num + value;
Enter fullscreen mode Exit fullscreen mode

When you see it at first time, you would react like "wtf???", but actually it's just closure. Function in function

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)