DEV Community

Kaziu
Kaziu

Posted on

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

Top comments (0)