Learn JavaScript Generators In 12 Minutes

preview_player
Показать описание

Generator functions in JavaScript are a feature most people think is useless, but in reality you can do a lot with generators. In this video I will be covering what generator functions are, how you can use them, and multiple real world examples of where generators are ideal.

📚 Materials/References:

🌎 Find Me Here:

⏱️ Timestamps:

00:00 - Introduction
00:28 - Generator Basics
05:24 - Generator Use Cases
09:10 - Generator Advanced Features

#JavaScriptGenerator #WDS #JavaScript
Рекомендации по теме
Комментарии
Автор

At 8:30, rather than using a for-loop, you can use the _yield*_ keyword because it lets you yield over iterables such as arrays, strings, etc.

Hence the code at 8:30 can be succinctly written:
function* generator(array) {
yield* array;
}

Side note: An arrow generator function does not exist.

zekumoru
Автор

Generators are useful when it's expensive to do each step of the yield. E.g., if you're hitting an API endpoint on each yield and you don't know how many results users will want, you can delay those API calls until they're actually needed.

olisaac
Автор

I personally never had a need to use a generator in JS. Still interesting content .

ukaszzbrozek
Автор

Just on Tuesday, I had an interview, and the interviewer asked me about generators. Unfortunately, I forgot about them, but passed the interview. Great stuff to revise, thanks!)

azizgofurov
Автор

Very interesting tutorial. 👍🏻👍🏻

I think at 8:05 it should have been

while (object.next().done === false)

Or simply

while (!object.next().done)

VivekMore
Автор

this is exactly what i am looking for ..I once saw this in redux saga but never truly understood how they work and proper use case..
but you explained it very simply and help to find use case and wow just clicked in mind that I need exactly something like this

kashifwahaj
Автор

I have used generator in a situation where I wanted to merge two arrays and do some mapping action on it. Generally you would need an extra variable to hold the result and pass it to the caller. But with generator you don't have to. Yield the line where this transformation happens and where it is called you can do a array.from

mthaha
Автор

JavaScript also includes the yield* keyword which allows recursive generator functions. I've used this before with graph traversal. Here is an example of a simple binary tree class with a recursive preorder generator:

class TreeNode {
constructor(value) {
this.value = value
this.left = null
this.right = null
}

*preorder() {
if (this.left !== null) {
yield* this.left.preorder()
}

yield this.value

if (this.right !== null) {
yield* this.right.preorder()
}
}
}

const root = new TreeNode(4)

root.left = new TreeNode(2)
root.left.left = new TreeNode(1)
root.left.right = new TreeNode(3)

root.right = new TreeNode(6)
root.right.left = new TreeNode(5)
root.right.right = new TreeNode(7)



kurtstephens
Автор

I found only 3 useful use cases for generators:
- iterators
- multiple returns from function (events, progress ...)
- chunk huge workload over multiple animation frames

korzinko
Автор

after C# with those IEnumerable, IEnumerator and yield which under the hood creates its own enumerator this is so easy )

ImmortalBest
Автор

To make it more obvious (to me) that yield can do two operations (return a value and insert a value via .next) would be like "const increment = yield id || 1; id += increment"

Great video. 👌👍👏

Norfeldt
Автор

A single take, to the point, nails the explination in an understandable way. Are you actually a robot? Your content is always the go-to when I'm having trouble with a pluralsight module.

dan
Автор

I've used generators some time ago. Mainly for learning purposes. Some Use cases for me were (mainly implementing Symbol.iterator so that I can use for of loop and rest operator):

1. If you want your object to have a working iterator, so that you can use for of loop in your object. Example:

const company = {
employees: ["kat", "manuel", "kris"],
[Symbol.iterator]: function* employeeGenerator() {
let curEmp = 0;
while (curEmp < this.employees.length) {
yield this.employees[curEmp];
curEmp += 1;
}

for (const emp of company) {
console.log(emp); // "kat", "manuel", "kris"
}


2. You can also use a spread operator if you implement symbol.iterator with a generator function.

const someIterable = {};

someIterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};

// you can spread the object like this


3. You can also parametrize your generator function and, for example, iterate over your iterable with some phrase:

function* countFruit(phrase) {

const fruits = ["apple", "banana", "peach"];
let curIndex = 0;

while (curIndex < fruits.length) {
yield phrase + fruits[curIndex];
curIndex += 1;
}
}

const fruitIterator = countFruit("A nice: ");

// A nice apple...
// A nice banana...
// A nice peach...

Krzysiekoy
Автор

I feel like it's best used for large scale applications with many interdependent systems waiting on a signal to continue to their next step in an infinite or very long cycle. This seems like a niche but very powerful tool that can't be easily replaced and I'm sad I can't figure out any other common use cases that map/acc already don't fill since it looks fun to implement.

singularity
Автор

Oh, you didn't talk about the coolest part that is you can loop through the generator values with a for loop and collect the values with the spread operator

gabrielmachado
Автор

I think it has a lot of benefits for example if you want to create multiple steps bar component that contains step 1, step 2, ...etc

mahmoudzakria
Автор

You can make a separate video comparing generators to the components from popular JS frameworks. All of them are of the same nature - a function with an internal state.

maximvoloshin
Автор

I happened to see it with React's Redux, But only now have I got to know real use cases. Thanks a lot for useful info

amilww
Автор

Incredible video as always, can't wait to see you reach 750K soon! :)

boiimcfacto
Автор

using it for frontend pagination could be an option actually

rajatsawarkar
join shbcf.ru