JavaScript generators are a powerful tool that often remains underestimated. And while most tasks can now be solved with async/await, today I'll show you how to use a JavaScript generator to create a unique ID generator.
Creating an ID Generator
First, let's create a function genId
. To begin with, we do not need to pass any arguments to it.
function genId() {
let id = 0;
id++;
}
However, if we now call this function, we will get undefined
, because our function does not return anything. To turn it into a generator, we need to add an asterisk (*
) after the word function
in the function declaration.
function* genId() {
let id = 0;
id++;
}
Let's assign our generator to a variable:
const gen = genId();
Now we can use our generator. The next
method is available, which allows us to get values from the generator in steps.
console.log(gen.next()); // { value: undefined, done: true }
The next
method returned us an object that has a value (value
), which is undefined
, and done
, which is true
. This is because inside the code of our function there is no moment when we would return something. To stop the generator and return a value, we need to use the yield
keyword.
function* genId() {
let id = 0;
yield id++;
}
Now everything has changed.
console.log(gen.next()); // { value: 0, done: false }
The function did not reach the end because it stopped on the word yield
. We can now copy this fragment several times:
function* genId() {
let id = 0;
yield id++;
yield id++;
yield id++;
}
console.log(gen.next()); // { value: 0, done: false }
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
ID Generator Using Loops
But that's not all. We can also create an ID generator using a while
loop that will run indefinitely until we stop it.
function* genId() {
let id = 0;
while (true) {
yield id++;
}
}
Now our generator will provide unique identifiers indefinitely, thanks to the use of the true
condition.
Generators in JavaScript are tools that are worth knowing and using. They are useful for handling asynchronous operations, generating data sequences and many other applications. I hope this article has helped you understand how to create and use ID generators in JavaScript.