Learn JavaScript Generators In 12 Minutes

  Рет қаралды 169,893

Web Dev Simplified

Web Dev Simplified

Күн бұрын

JavaScript Simplified Course: javascriptsimplified.com
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:
JavaScript Simplified Course: javascriptsimplified.com
Generators Article: blog.webdevsimplified.com/202...
🌎 Find Me Here:
My Blog: blog.webdevsimplified.com
My Courses: courses.webdevsimplified.com
Patreon: / webdevsimplified
Twitter: / devsimplified
Discord: / discord
GitHub: github.com/WebDevSimplified
CodePen: codepen.io/WebDevSimplified
⏱️ Timestamps:
00:00 - Introduction
00:28 - Generator Basics
05:24 - Generator Use Cases
09:10 - Generator Advanced Features
#JavaScriptGenerator #WDS #JavaScript

Пікірлер: 221
@zekumoru
@zekumoru Жыл бұрын
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.
@olisaac5080
@olisaac5080 2 жыл бұрын
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.
@siddhantjain2402
@siddhantjain2402 2 жыл бұрын
I believe you are talking about Pagination?
@ShadowVipers
@ShadowVipers Жыл бұрын
Wouldn't this require you to know how many yields to include? Say the number of results varies based on how many results can fit on their screen (auto-loading implementation). Then depending on the height of the screen, one user may only need one api request, another may require 2 requests... so if you have 2 yields wouldn't that block that first user from ever getting their results since the endpoint is still waiting on that second request to occur?
@awekeningbro1207
@awekeningbro1207 Жыл бұрын
Redux saga actually uses generators for async operations
@tomjones8293
@tomjones8293 Жыл бұрын
@@awekeningbro1207 saga is dead abandoned project
@ukaszzbrozek6470
@ukaszzbrozek6470 2 жыл бұрын
I personally never had a need to use a generator in JS. Still interesting content .
@richardkirigaya8254
@richardkirigaya8254 2 жыл бұрын
wait until you start using redux saga :)
@ukaszzbrozek6470
@ukaszzbrozek6470 2 жыл бұрын
@@richardkirigaya8254 I used to work with redux saga a long time ago. I now that it have generators under the hood. I wrote some generators for testing sagas. Thanks fo jogging my memory :)
@richardkirigaya8254
@richardkirigaya8254 2 жыл бұрын
@@ukaszzbrozek6470 Personally, out of everything in React, the only thing that gives me headache till today is redux saga
@Endrit719
@Endrit719 2 жыл бұрын
@@richardkirigaya8254 why is it necessary to use redux saga tho?
@richardkirigaya8254
@richardkirigaya8254 2 жыл бұрын
@@Endrit719 it's not really necessary to use, it's more of a preferred option than Thunk. Sagas are preferred over Thunk cos of "callback hell" + it's easier to test your async code with Saga over Thunk
@azizgofurov1575
@azizgofurov1575 2 жыл бұрын
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!)
@VivekMore1
@VivekMore1 2 жыл бұрын
Very interesting tutorial. 👍🏻👍🏻 I think at 8:05 it should have been while (object.next().done === false) Or simply while (!object.next().done)
@kashifwahaj
@kashifwahaj 2 жыл бұрын
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
@nativeKar
@nativeKar 2 жыл бұрын
I've been DYING for you to make EXACTLY this! Thanks!
@boiimcfacto2364
@boiimcfacto2364 2 жыл бұрын
Incredible video as always, can't wait to see you reach 750K soon! :)
@amilww
@amilww 2 жыл бұрын
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
@b7otato
@b7otato Жыл бұрын
As usual, great and simple explaination. Thank you
@dan110024
@dan110024 Жыл бұрын
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.
@joel_mathew
@joel_mathew 2 жыл бұрын
I love ur videos it really helps Thank u so much for these tutorials
@singularity1130
@singularity1130 2 жыл бұрын
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.
@simonadams4857
@simonadams4857 2 жыл бұрын
Thank you sir, your contents are always helpful. Keep the good work, well done
@Krzysiekoy
@Krzysiekoy 2 жыл бұрын
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; }; console.log([...someIterable]); // 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: "); console.log(fruitIterator.next()); // A nice apple... console.log(fruitIterator.next()); // A nice banana... console.log(fruitIterator.next()); // A nice peach...
@shivanshpratap3624
@shivanshpratap3624 2 жыл бұрын
So, in the first example here, What is the difference if we use map function to loop over the employees array and by iterating it by using a generator. Please explain
@explore-learn-share6937
@explore-learn-share6937 2 жыл бұрын
Very well explained. Thank you making such useful and informative videos
@maximvoloshin7602
@maximvoloshin7602 2 жыл бұрын
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.
@dennis87ist
@dennis87ist 2 жыл бұрын
Very clear! Thank you so much man!
@wawayltd
@wawayltd Жыл бұрын
Kyle saves the day again! Thank You!... Just trying to get into Redux-Saga, so that was really helpful.👍
@jsmunroe
@jsmunroe Ай бұрын
This is the heart and soul of LINQ and delayed execution. I need to write a LINQ-like package. That would be so much fun!
@bas_kar_na_yar
@bas_kar_na_yar 2 жыл бұрын
This might come handy in creating something like a mock API for testing your system or as a placeholder.
@bineetnaidu5146
@bineetnaidu5146 2 жыл бұрын
Interesting... I learned something new today.
@mthaha2735
@mthaha2735 2 жыл бұрын
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
@sortirus
@sortirus 2 жыл бұрын
Could you provide an example? Because I normally would use spread syntax to merge two arrays and then map them in your example.
@mraravind1111
@mraravind1111 2 жыл бұрын
@@sortirus Yeah I use both spread and concat
@stcm
@stcm 2 жыл бұрын
@@sortirus In this context I think they are using a zipper merge where each element of the final array is some combination of the elements of the same index in the original arrays. (e.g. outArr[i] = {...inArrA[i], ...inArrB[i]} - although the object could be more complex than that) This would allow you to do multiple operations on that object before setting it's value in the final array (kind of like arrA.zip(arrB).map().map().map()). It's not a perfect analogy but hopefully gets the point across.
@cyril7104
@cyril7104 2 жыл бұрын
Thx for video, explanation for fancy Reflect would be amazingly usefull :)
@DaveGalligher
@DaveGalligher 2 жыл бұрын
Great explanation, thank you.
@rei.orozco
@rei.orozco 2 жыл бұрын
Thanks a lot, very clear explanation
@rodrigomatiasdesouza845
@rodrigomatiasdesouza845 Жыл бұрын
Thanks so much for the video. It's really good.
@geneanthony3421
@geneanthony3421 2 жыл бұрын
I first heard about generators in Python and the concept seems quite nice (although haven't done much Python since to use them yet). Should allow for less resources tied up at once and cleaner code since you don't need to call a function from a function (since it just returns the latest result to whatever called it who can then do what it wants with it).
@sanketwakhare27
@sanketwakhare27 2 жыл бұрын
Great video. Thanks!
@kushagragarg4370
@kushagragarg4370 2 жыл бұрын
Thanks, It really helped a lot.
@Guihgo
@Guihgo 2 жыл бұрын
Tks só much! Best tutorial
@imaaduddin7715
@imaaduddin7715 2 жыл бұрын
Great video! Appreciate it!
@Ballistic_Bytes
@Ballistic_Bytes 2 жыл бұрын
Brilliant explaination
@johncerpa3782
@johncerpa3782 2 жыл бұрын
Good explanation 👍🏼
@korzinko
@korzinko 2 жыл бұрын
I found only 3 useful use cases for generators: - iterators - multiple returns from function (events, progress ...) - chunk huge workload over multiple animation frames
@AjithKumar-te4fp
@AjithKumar-te4fp 8 ай бұрын
Hey @korzinko i have one question to you. if multiple returns. why can't we use conditional statements? please clear this.
@korzinko
@korzinko 8 ай бұрын
@@AjithKumar-te4fp convenience and cleaner code. If you have a code, that can produce multiple values over the time, e.g. long running task with progress (storing 1000+ rows in DB, upload of large file...) or lazy evaluation(expensive DOM traversal), it's convenient to hide it inside the generator. Without it, you would either polute global scope with variables or reinvent the same logic in object/class/closure. Generators are not something you will not use daily , but occasionally they are handy.
@AjithKumar-te4fp
@AjithKumar-te4fp 8 ай бұрын
@@korzinko 👍 agreed
@ImmortalBest
@ImmortalBest 2 жыл бұрын
after C# with those IEnumerable, IEnumerator and yield which under the hood creates its own enumerator this is so easy )
@erfelipe
@erfelipe 2 жыл бұрын
Great explanation.
@khalednasr7952
@khalednasr7952 2 жыл бұрын
Good video as always!
@rezaghaemifar5703
@rezaghaemifar5703 Жыл бұрын
What a perfect explanation
@kurtstephens9409
@kurtstephens9409 2 жыл бұрын
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) console.log(...root.preorder())
@abdellahcodes
@abdellahcodes 2 жыл бұрын
For the example array, you could simply `yield* arr` or any other iterable for that matter l, including other generators
@adnan19672000
@adnan19672000 Жыл бұрын
HI, I'm following your videos lately, and I liked them a lot. I wonder if you can make a new video about "generator composition" because its idea is not very clear to me. Thank you.
@yoscbd
@yoscbd 2 жыл бұрын
Great content! :)
@BartBruh
@BartBruh 11 ай бұрын
You are amazing bro!
@gabrielmachado5708
@gabrielmachado5708 2 жыл бұрын
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
@erikawwad7653
@erikawwad7653 2 жыл бұрын
Used this at work! felt like a badass
@rahulxdd
@rahulxdd 2 жыл бұрын
@@erikawwad7653 @Gabriel Machado Can I see an example please?
@Hendika
@Hendika 2 жыл бұрын
Example code would be very helpful :D
@Yous0147
@Yous0147 2 жыл бұрын
So if I'm understanding correctly, what you can do is define a generator to do whatever calculations you want and then collect each value in a for loop? So like: function* geometricGenerator(){ let num = 1; while(true){ yield num num*2 } } const geometricList = []; const generator = geometricGenerator(); for(var i = 0; i < 10; i++){ geometricList.push(generator.next()); } I am not sure how to do this with the spread operator though
@Italiafani
@Italiafani 2 жыл бұрын
​@@Hendika // Generator function with an exit condition function* myGenFun () { let i = 0 while (i < 5) yield i++ } // Spread const myArr = [...myGenFun()] // or console.log(...myGenFun()) // Use in a for loop for (const i of myGenFun()) console.log(i) // Your program will obviously run out of memory if you try to // use the spread operator with a generator function where // there's no exit condition. Same goes for the for loop, unless // of course you break out of the loop yourself, like so: function* powers (n) { for (let current = n;; current *= n) { yield current } } for (const power of powers(2)) { if (power > 32) break console.log(power) // 2, 4, 8, 16, 32 }
@erikawwad7653
@erikawwad7653 2 жыл бұрын
got to use this at work and it just fit the solution
@TateClips_1
@TateClips_1 2 жыл бұрын
your channel is the best bro
@Norfeldt
@Norfeldt 2 жыл бұрын
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. 👌👍👏
@vukkulvar9769
@vukkulvar9769 2 жыл бұрын
You could confuse (yield id) || 1 and yield (id || 1)
@mishasawangwan6652
@mishasawangwan6652 2 жыл бұрын
just a nitpit suggestion: if you turn up the ‘release’ parameter on your gate, the vocal audio would sound much smoother.
@saransurya8929
@saransurya8929 2 жыл бұрын
Hello Kyle, can we have a video in how to create a custom debugger for javascript ?, That'll be more interesting... ✌🏼 And also love your content ❤️
@ryzs_
@ryzs_ 2 жыл бұрын
After many youtube videos I watch explaining about generator, this one most accurate! Finally i can move on 😂
@Petriu1
@Petriu1 2 жыл бұрын
A cool use for these would be to return different class names or other animation/styling behaviours, where excessive code is not needed. Simple just yield return another class when clicked on something.
@jasonhuang4333
@jasonhuang4333 2 жыл бұрын
Kyle you are the best!
@subinkv6849
@subinkv6849 2 ай бұрын
Great content..
@danial668
@danial668 2 жыл бұрын
Nice explanation
@bhaveshverma8629
@bhaveshverma8629 2 жыл бұрын
Very good tutorial
@rajatsawarkar
@rajatsawarkar 2 жыл бұрын
using it for frontend pagination could be an option actually
@mahmoudzakria6946
@mahmoudzakria6946 Ай бұрын
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
@balazsgyekiczki1140
@balazsgyekiczki1140 2 жыл бұрын
Very nice!
@Nick12_45
@Nick12_45 Ай бұрын
Thanks!
@anbor7778
@anbor7778 2 жыл бұрын
i don't know why this channel is not growing😕 man, good work really appreciate
@GbpsGbps-vn3jy
@GbpsGbps-vn3jy 2 жыл бұрын
Because these days JS yield too many features that are pointless to use in general purpose front/end coding
@cw3dv
@cw3dv 2 жыл бұрын
Awesome video! but there is some problem with your microphone or the controller IG
@7billon680
@7billon680 2 жыл бұрын
Lovely content❤️❤️❤️❤️❤️
@alphacubeastraja
@alphacubeastraja 2 жыл бұрын
Great content, one question though, why you don't use semicolons? Lack of semicolons would work in all js scripts?
@moiserwibutso4899
@moiserwibutso4899 2 жыл бұрын
Thanks a lot.
@arunprakash9736
@arunprakash9736 2 жыл бұрын
It would be useful if you do a video on co npm module. I saw thatused in many places, but it is hard to understand
@Kanexxable
@Kanexxable 2 жыл бұрын
I want to make a blog site eventually and use a CMS to manage the site which one do i pick contentful strapi or ghost which is the best one
@JasimGamer
@JasimGamer 2 жыл бұрын
You can also function* gen(){ yield...... } let g = gen() arr = [...g] console.log(arr) or console.log([...g)
@akifcankara2225
@akifcankara2225 2 жыл бұрын
i think we can use generators also for submiting form. First validate the input fields after call next and send request to api
@ChrisAthanas
@ChrisAthanas 2 жыл бұрын
The best tutorials
@milankbudha
@milankbudha 2 жыл бұрын
thank u so much
@dhawalparmar7117
@dhawalparmar7117 2 жыл бұрын
Best youtube channel for Js
@petarkolev6928
@petarkolev6928 2 жыл бұрын
Amazing explanation! But I am confused why do we need not to do strict comparison? I mean the code from the video works fine (I am talking about the generateId() example) but when I write it down with a strict comparison, e.g. increment !== null I yield only 1 and the rest is undefined and done. Why is that?
@camotubi
@camotubi 2 жыл бұрын
Is there any difference between creating a generator function and creating an object that implements the iterator protocol? Or is it like async await and .then, .catch that they are syntactically different but allow you to do the same thing?
@nathanielnizard2163
@nathanielnizard2163 2 жыл бұрын
iterator Symbol plz. I think the best thing to do is to promise chain them because generators have already a throw feature when things go wrong, it is meant to be "plugged" this way I think.
@miw879
@miw879 2 жыл бұрын
SIR THANK YOU FOR EXISTING
@nhantrong7395
@nhantrong7395 2 жыл бұрын
Thanks bro
@sh4kirrr448
@sh4kirrr448 2 жыл бұрын
Could you please make a video on Symbol.asyncIterator and how they are useful?
@mtranchi
@mtranchi 2 жыл бұрын
So I can see the value with generating id's and with iterating over arrays. Any other real-world use cases? I'm asking because offhand I can't think of any.
@meganadams7274
@meganadams7274 2 жыл бұрын
I was thinking what about using it to click through frames, like in a slideshow or something?
@manit77
@manit77 2 жыл бұрын
Old code, you don't need it anymore.
@plsreleasethekraken
@plsreleasethekraken 11 ай бұрын
At 7:30, unfortunately when you express Object.next() to check the done property, you're releasing the value and won't have access to it again inside the while loop without some assignment.
@ashoksoni8931
@ashoksoni8931 2 жыл бұрын
at 10:17 how do we go below our line of code then back above to yield the new id ?
@yashojha5033
@yashojha5033 2 жыл бұрын
Awesome. Thanks. But I didn't understand at 10:33 how passing a value to yield affected the response of the same iteration.
@vukkulvar9769
@vukkulvar9769 2 жыл бұрын
the previous yield provides the argument, loop through, the current yield return the updated value using the argument first loop yield 1 second loop const increment = 4 yield 5
@Larpus
@Larpus 2 жыл бұрын
So, basically what Tim Corey said on his video few days ago about Yield in C#
@alexanderhorl6602
@alexanderhorl6602 2 жыл бұрын
The infinite loop like you showed it could be written as a closure instead of a generator too, right?
@ttbooster
@ttbooster 2 жыл бұрын
Is this only aplicable for JS or is it possible in TypeScript as well, say Angular? What would the syntax be?
@antwanwimberly1729
@antwanwimberly1729 6 ай бұрын
ECMA needs a more universal standard . We’re working on it but thanks babel for getting up ahead
@AnkurShah_CS
@AnkurShah_CS 2 жыл бұрын
Should we use it in backend for creating id's ?? Any pros/cons ??
@yahyeabdirashid9716
@yahyeabdirashid9716 2 жыл бұрын
Thanks
@TECPABLO
@TECPABLO 2 жыл бұрын
very good
@EGOmaniack77
@EGOmaniack77 2 жыл бұрын
you forgot about one thing. you can spread generators like so [...getenaror()]. Or your can spread all objects witch have Symbol iterator in it like so [...{ [Symbol.iterator]: generator }]
@artgreg2296
@artgreg2296 2 жыл бұрын
Thanks mr Kyle (i dont know if you noticed each time my comments on your vid) but this time you did not cover "yield delegation" neither async generator...
@bazy1983
@bazy1983 2 жыл бұрын
Can this replace recursive function call?
@RawMilkEnthusiast
@RawMilkEnthusiast 2 жыл бұрын
So when you’re passing a number to next(), you don’t need to add parameters to the generator function for it to take that number as an argument?
@ygormartinsr
@ygormartinsr 2 жыл бұрын
Only if he had manually declared next()
@thewiseperspectiveoriginal
@thewiseperspectiveoriginal 2 жыл бұрын
Hi Kyle, do you have certification for your courses?, basically a certificate of completion
@WebDevSimplified
@WebDevSimplified 2 жыл бұрын
All my courses have certificates for completion
@filenko45
@filenko45 2 жыл бұрын
Make a video about symbol type in JS please 🙏
@nitsanbh
@nitsanbh Жыл бұрын
As Douglas Crockford said, everything you can do with generators, can be easily done with just functions, if you understand how to use closure
@EmptyGlass99
@EmptyGlass99 2 жыл бұрын
exactly the same as 'yield return' in C# which creates an object of type IEnumerable
@shaik_mohammedimran
@shaik_mohammedimran 2 жыл бұрын
Nice, What is prototype in JS
@mohammedpapad2202
@mohammedpapad2202 2 жыл бұрын
Nice
@JohnnieWalkerGreen
@JohnnieWalkerGreen 2 жыл бұрын
Will the unused generated objects automatically be deleted/destroyed?
@rem7412
@rem7412 Жыл бұрын
don't JS have garbage collection?
@alii4334
@alii4334 2 жыл бұрын
Will that be useful for infinite scrolling?
5 MORE Must Know JavaScript Features That Almost Nobody Knows
18:05
Web Dev Simplified
Рет қаралды 179 М.
Async Generators - Javascript In Depth
38:33
Tech with Nader
Рет қаралды 2,1 М.
Кәріс тіріма өзі ?  | Synyptas 3 | 8 серия
24:47
kak budto
Рет қаралды 1,7 МЛН
Let's all try it too‼︎#magic#tenge
00:26
Nonomen ノノメン
Рет қаралды 54 МЛН
Super sport🤯
00:15
Lexa_Merin
Рет қаралды 11 МЛН
All The JavaScript You Need To Know For React
28:00
PedroTech
Рет қаралды 538 М.
10 Tailwind Classes I Wish I Knew Earlier
13:31
Web Dev Simplified
Рет қаралды 154 М.
The Power of JS Generators by Anjana Vakil
36:10
JSConf
Рет қаралды 159 М.
Learn JavaScript Event Listeners In 18 Minutes
18:03
Web Dev Simplified
Рет қаралды 562 М.
How To Create/Use Functions - JavaScript Essentials
9:34
Web Dev Simplified
Рет қаралды 108 М.
Using async generators to stream data in JavaScript
27:37
Fun Fun Function
Рет қаралды 34 М.
Learn JavaScript DOM Traversal In 15 Minutes
14:44
Web Dev Simplified
Рет қаралды 218 М.
Learn JSON in 10 Minutes
12:00
Web Dev Simplified
Рет қаралды 3,1 МЛН
Junior Vs Senior Code - How To Write Better Code
22:13
Web Dev Simplified
Рет қаралды 1,1 МЛН
JavaScript ES6 Arrow Functions Tutorial
9:32
Web Dev Simplified
Рет қаралды 810 М.