DEV Community

machy44
machy44

Posted on • Edited on

Take advantage of closure

I had an interesting question in a technical interview. I had to create function which output behaves this way.

counter() // 0
counter() // 1
counter() // 2
Enter fullscreen mode Exit fullscreen mode

Each time counter is executed it should log number incremented by one. I immediately realized the idea of interviewer was to see if I understand closures.

This was my solution.

const counter = (() => {
  let count = -1;
  return () => {
    console.log(++count); 
  };
})()


counter();
counter();
counter();
counter();

Enter fullscreen mode Exit fullscreen mode

As you could see I also used Immediately Invoked Function Expression (IIFE) which creates its own scope instantly.

Conclusion

The more experienced I am, the more I realize how important is Javascript: The good parts book. Most of the abstractions used in js libraries/frameworks are implemented above ideas described in this book.
If you want know more about closures you can read about them in chapter 4 (section Closure).

Top comments (0)