Write a program that prints two alternate colors using JavaSript closures
The problem
Write a program that prints two alternate colors such as red
and green
using JavaScript closures.
The problem description
In this problem, we need to make use of JavaScript closures. We need to write a function where we can not use any global variable or scope. We are not allowed to change the following function signature:
const redGreen = () => { } redGreen(); // red redGreen(); // Green redGreen(); // red redGreen(); // Green redGreen(); // red redGreen(); // Green redGreen(); // red redGreen(); // Green
The problem solution
const redGreen = (() => { color = 'red'; return () => { console.log(color); color = (color === 'red') ? 'green' : 'red'; } })();