Learn JavaScript Generators In 12 Minutes

Поділитися
Вставка
  • Опубліковано 30 вер 2024

КОМЕНТАРІ • 231

  • @ukaszzbrozek6470
    @ukaszzbrozek6470 3 роки тому +219

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

    • @richardkirigaya8254
      @richardkirigaya8254 3 роки тому +20

      wait until you start using redux saga :)

    • @ukaszzbrozek6470
      @ukaszzbrozek6470 3 роки тому +5

      @@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 3 роки тому +4

      @@ukaszzbrozek6470 Personally, out of everything in React, the only thing that gives me headache till today is redux saga

    • @Endrit719
      @Endrit719 3 роки тому +3

      @@richardkirigaya8254 why is it necessary to use redux saga tho?

    • @richardkirigaya8254
      @richardkirigaya8254 3 роки тому +1

      @@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

  • @olisaac5080
    @olisaac5080 3 роки тому +151

    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 3 роки тому +28

      I believe you are talking about Pagination?

    • @ShadowVipers
      @ShadowVipers 2 роки тому +2

      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 Рік тому +1

      @@awekeningbro1207 saga is dead abandoned project

    • @n8o_
      @n8o_ 3 місяці тому

      It sounds like this is just abstracting away the state needed to accomplish something like pagination

  • @zekumoru
    @zekumoru Рік тому +60

    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.

    • @Exploretheworld-yw7yc
      @Exploretheworld-yw7yc 2 місяці тому

      this works because array also have generator function inside it right ? Like when we do next we ask array to yield and pass that yield back.

    • @zekumoru
      @zekumoru 2 місяці тому

      @@Exploretheworld-yw7yc It doesn't have anything to do with generator functions actually. It has something to do with how the yield* operator works, as the MDN docs state: "The yield* operator is used to delegate to another iterable object, such as a Generator."
      TL;DR: In simple terms, yield* operates on iterables and arrays are iterable objects. And an extra terminology, the objects returned by function generators are called "Generator" objects which are also iterables.
      Notice the word "iterable", what's an iterable? It just basically means that an object, let's name it A , must have the @@iterator method, a.k.a. [Symbol.iterator](), which returns an object (which could be another object B or A itself) that conforms to the iterator protocol. Iterator protocol basically means that an object must have a next() method returning another object C which contains a "value" field, which will be used when next() is called, or a "done" field, indicating that the iteration is finished. Arrays are built-in iterables and that is why we can use the yield* operator on them.
      Here's an example showing an implementation of an iterable object which is then used inside a function generator using the yield* operator:
      const iterableObj = { // This is object A
      [Symbol.iterator]() {
      let i = 0;
      const iteratorObj = { // This is object B
      next() {
      if (i >= 10) return { done: true }; // This is object C
      return { value: i++ }; // Or this is object C
      },
      };
      return iteratorObj;
      },
      };
      const createGenerator = function* () {
      yield* iterableObj;
      };
      const generator = createGenerator();
      for (let result; !(result = generator.next()).done; ) {
      console.log(result.value);
      }

    • @zekumoru
      @zekumoru 2 місяці тому +2

      It doesn't have anything to do with generator functions actually. It has something to do with how the yield* operator works, as the MDN docs state: "The yield* operator is used to delegate to another iterable object, such as a Generator."
      TL;DR: In simple terms, yield* operates on iterables and arrays are iterable objects. Also, "Generator" are the objects returned by function generators.
      Notice the word "iterable", what's an iterable? It just basically means that an object, let's name it A, must have the @@iterator method, a.k.a. [Symbol.iterator](), which returns an object (which could be another object B or A itself) that conforms to the iterator protocol. Iterator protocol basically means that an object must have a next() method returning another object C which contains a "value" field, which will be used when next() is called, or a "done" field, indicating that the iteration is finished. Arrays are built-in iterables and that is why we can use the yield* operator on them.
      Here's an example showing an implementation of an iterable object which is then used inside a function generator using the yield* operator:
      const iterableObj = { // This is object A
      [Symbol.iterator]() {
      let i = 0;
      const iteratorObj = { // This is object B
      next() {
      if (i >= 10) return { done: true }; // This is object C
      return { value: i++ }; // Or this is object C
      },
      };
      return iteratorObj;
      },
      };
      const createGenerator = function* () {
      yield* iterableObj;
      };
      const generator = createGenerator();
      for (let result; !(result = generator.next()).done; ) {
      console.log(result.value);
      }
      Therefore no, arrays don't have a generator function inside them. It's because arrays are iterables and yield* operates on iterables.

  • @dasten123
    @dasten123 3 роки тому +8

    I'm a little disappointed :| But don't feel bad, nobody was ever able to show me an example where a generator function was _actually_ useful.
    Everything you showed us in this video could _easily_ be done with a custom object that implements the next() function and keeps track on how often it was called. The only difference of using generator functions (except from a few less lines of code) is that everyone reading the code who hasn't used it yet, will be super confused.
    I would totally love to see an _actual_ good real-world use case. But I doubt there is one :/ I mean it's cool but it's really just a gimmick

    • @yarngoblyn
      @yarngoblyn 3 роки тому

      I would use it for the next project with EventSource. My solution till now is a feeding the EventSource in the algorithmic function (ex. PDF splitting, CSV rearranging, ...) by calling a callback from the function arguments. But the function are not the right place for this. They should only managing their specific part, not the network things. In the future the calling network endpoint will be waiting for yields, enrich them and send the events to the EventSource socket.

  • @azizgofurov1575
    @azizgofurov1575 3 роки тому +11

    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!)

  • @korzinko
    @korzinko 3 роки тому +31

    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 Рік тому

      Hey @korzinko i have one question to you. if multiple returns. why can't we use conditional statements? please clear this.

    • @korzinko
      @korzinko Рік тому

      @@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 Рік тому

      @@korzinko 👍 agreed

  • @gabrielmachado5708
    @gabrielmachado5708 3 роки тому +31

    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 3 роки тому +3

      Used this at work! felt like a badass

    • @rahulxdd
      @rahulxdd 3 роки тому +3

      @@erikawwad7653 @Gabriel Machado Can I see an example please?

    • @Hendika
      @Hendika 3 роки тому +2

      Example code would be very helpful :D

    • @Yous0147
      @Yous0147 3 роки тому +1

      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 3 роки тому +9

      ​@@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
      }

  • @rajatsawarkar
    @rajatsawarkar 3 роки тому +9

    using it for frontend pagination could be an option actually

  • @VivekMore1
    @VivekMore1 3 роки тому +58

    Very interesting tutorial. 👍🏻👍🏻
    I think at 8:05 it should have been
    while (object.next().done === false)
    Or simply
    while (!object.next().done)

  • @d.l.3807
    @d.l.3807 2 роки тому +1

    Somehow I don't get the part with adding a value to the increment id. I am confused by this line:
    const increment = yield id
    So, first run it stops there, I guess. Why would it stop there? Isn't increment = null? And why would it stop when it's just a declaration of a variable? But id=1 gets printed out.
    Second run, yield now has a value of 4. The code runs over the if statement and checks for increment = null. Why is increment now not null? Why is yield id now something? I would read this as ''4 1". 4 being the value of yield and 1 the current index. But this doesn't make sense. The addition is inside the if statement. Why is increment now 4 and not 4 1? Also, why is increment null if .next() is not given a value? Can anyone understand my issue here? ^^

  • @mthaha2735
    @mthaha2735 3 роки тому +40

    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 3 роки тому +19

      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 3 роки тому

      @@sortirus Yeah I use both spread and concat

    • @stcm
      @stcm 3 роки тому

      @@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.

  • @paulcrowder
    @paulcrowder 3 роки тому +2

    Your lack of semicolons drives me insane.

  • @davi48596
    @davi48596 4 місяці тому +1

    I imagine myself using this in a 3 step checkout shopping cart using an api for example

  • @mtranchi
    @mtranchi 3 роки тому +7

    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 3 роки тому +1

      I was thinking what about using it to click through frames, like in a slideshow or something?

    • @manit77
      @manit77 3 роки тому +2

      Old code, you don't need it anymore.

  • @ImmortalBest
    @ImmortalBest 3 роки тому +4

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

  • @plsreleasethekraken
    @plsreleasethekraken Рік тому +1

    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.

  • @EGOmaniack77
    @EGOmaniack77 3 роки тому +1

    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
    }]

  • @ashoksoni8931
    @ashoksoni8931 2 роки тому +1

    at 10:17 how do we go below our line of code then back above to yield the new id ?

  • @JohnnieWalkerGreen
    @JohnnieWalkerGreen 3 роки тому +3

    Will the unused generated objects automatically be deleted/destroyed?

    • @rem7412
      @rem7412 Рік тому +1

      don't JS have garbage collection?

  • @adnan19672000
    @adnan19672000 2 роки тому +1

    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.

  • @kirillvoloshin2065
    @kirillvoloshin2065 3 роки тому +1

    I am new to generators, but doesn't the code at 7:43 have to be
    Object.next().done !== true ?

  • @boiimcfacto2364
    @boiimcfacto2364 3 роки тому +3

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

  • @tom-on
    @tom-on 3 місяці тому +1

    No that's a function pointer :)

  • @joel_mathew
    @joel_mathew 3 роки тому +3

    I love ur videos it really helps Thank u so much for these tutorials

  • @singularity1130
    @singularity1130 3 роки тому +3

    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.

  • @ahmedikawika2204
    @ahmedikawika2204 Рік тому +1

    I don't get the use of generator function

  • @Guihgo
    @Guihgo 2 роки тому

    Tks só much! Best tutorial

  • @kurtstephens9409
    @kurtstephens9409 3 роки тому +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())

  • @ShootingUtah
    @ShootingUtah 6 місяців тому

    Still very confused as to how next(4) passes the value of 4 into the increment variable? You would think your generator function would need to take in that parameter?! What dark magic is going on here?

  • @Larpus
    @Larpus 3 роки тому +1

    So, basically what Tim Corey said on his video few days ago about Yield in C#

  • @kashifwahaj
    @kashifwahaj 3 роки тому +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

  • @maximvoloshin7602
    @maximvoloshin7602 3 роки тому +3

    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.

  • @d0minar
    @d0minar 19 днів тому

    Not exactly everything. You did not show how generator can call another generator. But thanks anyway. Good job.

  • @thomasoa
    @thomasoa Рік тому

    It would have been nice to have an example of while(!generator.next().done) {} where you still access the value. It is not obvious how to do that, except something like: while(!(result =generator.next()).done) { value =result.value; ... } That seems cumbersome

  • @Krzysiekoy
    @Krzysiekoy 3 роки тому +15

    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 3 роки тому

      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

  • @camotubi
    @camotubi 3 роки тому +3

    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 3 роки тому

      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.

  • @bineetnaidu5146
    @bineetnaidu5146 3 роки тому +3

    Interesting... I learned something new today.

  • @Abulkhair1995
    @Abulkhair1995 Рік тому +1

    I really like your HAIR

  • @zerosugarmatcha7348
    @zerosugarmatcha7348 3 роки тому

    Wow, I didn't realize you can write Javascript without semicolons, you probably came from Python?

  • @col.petirivchenko6949
    @col.petirivchenko6949 4 місяці тому

    On the segment using the increment variable, it wasn't explained where the arguments would be assigned in the generator function. Is there something I'm missing here? Anyone welcome to comment. Thanks in advance.

  • @manit77
    @manit77 3 роки тому +1

    I really don't see a need for generators. The real benefit, is they allow you to maintain a state and pass them around. You can do the same with global variables or classes.

  • @gmkhussain
    @gmkhussain 3 роки тому

    JavaScript is easy for 2 people.
    One who knows JavaScript actually
    & other one who just know JavaScript is easy. 😂

  • @antwanwimberly1729
    @antwanwimberly1729 11 місяців тому

    ECMA needs a more universal standard . We’re working on it but thanks babel for getting up ahead

  • @ryanpeplinski1884
    @ryanpeplinski1884 3 роки тому

    Wow, that’s useless. How about building something useful. Like a number or name generator?

  • @mahmoudzakria6946
    @mahmoudzakria6946 5 місяців тому

    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

  • @bardavidi3949
    @bardavidi3949 Рік тому

    good tutorial, but why in some parts do you talk like your'e on x3 playback speed?

  • @pranavbhat29
    @pranavbhat29 3 роки тому

    8:07,Isn't it while(object.next().done === false )?

  • @wawayltd
    @wawayltd Рік тому

    Kyle saves the day again! Thank You!... Just trying to get into Redux-Saga, so that was really helpful.👍

  • @tahirsaeed99ts
    @tahirsaeed99ts 3 роки тому +1

    is it just me or is javascript really the most weird language among all other languages...

    • @ariMuayad
      @ariMuayad 3 роки тому

      It certainly is one of the weirdest of them.

    • @kristofferjohansson3768
      @kristofferjohansson3768 3 роки тому

      I agree. It feels like everything goes and really need to be disciplined to avoid ‘spaghetti code’.

  • @bas_kar_na_yar
    @bas_kar_na_yar 3 роки тому +1

    This might come handy in creating something like a mock API for testing your system or as a placeholder.

  • @simonadams4857
    @simonadams4857 3 роки тому +1

    Thank you sir, your contents are always helpful. Keep the good work, well done

  • @Nick12_45
    @Nick12_45 6 місяців тому +1

    Thanks!

  • @rodrigomatiasdesouza845
    @rodrigomatiasdesouza845 Рік тому

    Thanks so much for the video. It's really good.

  • @Norfeldt
    @Norfeldt 3 роки тому +1

    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 3 роки тому

      You could confuse (yield id) || 1 and yield (id || 1)

  • @sinom
    @sinom Рік тому

    It's stupid that you still can't use generators with arrow functions

  • @pro-cr2eo
    @pro-cr2eo 3 роки тому +2

    If wanna learn Redux-saga, learn this damn thing

    • @Rppiano
      @Rppiano 3 роки тому +1

      Can you explain a little bit more? What's the relation?

  • @uchennachukwuba
    @uchennachukwuba 11 місяців тому

    The yield keyword acts like a return statement that can be called with a next method

  • @lauris5275
    @lauris5275 2 роки тому

    I always forget how to use them and when to use them. Need to repeat everytime.

  • @janimakinen1455
    @janimakinen1455 Рік тому

    this was interesting. with that said, javascript is the worst thing to have happened for the internet.

  • @fwlo4409
    @fwlo4409 3 роки тому

    LetmeKnow the function that allows me to set up hair like yours

  • @kvirajs
    @kvirajs 2 роки тому

    If i am not wrong this can be used to deep clone objects.

  • @numerobis3949
    @numerobis3949 2 роки тому

    generators are a type of iterators who are a type of shermanators

  • @mynameiskranz
    @mynameiskranz 2 роки тому

    this reminds me of how the expressjs middleware works

  • @JasimGamer
    @JasimGamer 3 роки тому

    You can also
    function* gen(){
    yield......
    }
    let g = gen()
    arr = [...g]
    console.log(arr)
    or
    console.log([...g)

  • @alii4334
    @alii4334 3 роки тому

    Will that be useful for infinite scrolling?

  • @ManoToor
    @ManoToor 3 роки тому

    is the audio when he talks cuttign in and out for anyone else?

  • @marcelfischer7815
    @marcelfischer7815 3 роки тому

    omg, please use uuids for primary keys..

  • @imtanuki4106
    @imtanuki4106 Рік тому

    I just want to know where you get your coffee...

  • @alphacubeastraja
    @alphacubeastraja 3 роки тому

    Great content, one question though, why you don't use semicolons? Lack of semicolons would work in all js scripts?

  • @WiredStudio
    @WiredStudio 3 роки тому

    @WebDevSimplified why don't you check falsy values like-
    if(!increment) //this will check for all falsy values like 0, false, undefinied, empty string, & null
    if(increment) //this will check all truly values like true, 1, length etc

  • @donaldklopper
    @donaldklopper Рік тому

    Interesting memory leak generator...

  • @jsmunroe
    @jsmunroe 6 місяців тому

    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!

  • @dhawalparmar7117
    @dhawalparmar7117 3 роки тому

    Best youtube channel for Js

  • @thanveerahmed1963
    @thanveerahmed1963 3 місяці тому

    Seriously Awesome content

  • @brhh
    @brhh 3 роки тому

    arrow function generator available?

  • @maciej12345678
    @maciej12345678 2 роки тому

    So when iterator is generator and vice versa ?

  • @nitsanbh
    @nitsanbh 2 роки тому

    As Douglas Crockford said, everything you can do with generators, can be easily done with just functions, if you understand how to use closure

  • @shaik_mohammedimran
    @shaik_mohammedimran 3 роки тому

    Nice, What is prototype in JS

  • @hybridboy9_9
    @hybridboy9_9 3 роки тому

    make video on "Symbols in js"

  • @yewwowduck
    @yewwowduck 3 роки тому

    so it's an enumerator?
    Why does javascript insist on renaming everything. It literally just makes it that much harder to find and search for features, let alone _talk to eachother_

  • @petarkolev6928
    @petarkolev6928 3 роки тому

    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?

  • @jujijiju6929
    @jujijiju6929 3 роки тому +3

    What does a generator do that a closure doesn't already allow me to do? I've sometimes wondered about that... It's suspending computation pre-emptively with yield, closures let me do the same thing in many cases.

  • @heinhtetzaw9463
    @heinhtetzaw9463 3 роки тому

    Make a video on Symbol keyword

  • @miw879
    @miw879 2 роки тому

    SIR THANK YOU FOR EXISTING

  • @tylerxie1042
    @tylerxie1042 2 роки тому

    Sounds like a state machine to me.

  • @cyril7104
    @cyril7104 3 роки тому

    Thx for video, explanation for fancy Reflect would be amazingly usefull :)

  • @ttbooster
    @ttbooster 3 роки тому

    Is this only aplicable for JS or is it possible in TypeScript as well, say Angular? What would the syntax be?

  • @geisonmcd
    @geisonmcd 2 роки тому

    I don't think you explicitly mentioned that yield is called yield because the code stops on it and will continue running after you call myGenerator.next() again

  • @dan110024
    @dan110024 2 роки тому

    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.

  • @EmptyGlass99
    @EmptyGlass99 3 роки тому

    exactly the same as 'yield return' in C# which creates an object of type IEnumerable

  • @Petriu1
    @Petriu1 3 роки тому

    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.

  • @artgreg2296
    @artgreg2296 3 роки тому

    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...

  • @tusharkumar2077
    @tusharkumar2077 17 днів тому

    This is very useful 😁

  • @KishanFX
    @KishanFX 3 роки тому

    One more real life example would be
    If you have list of some items and when you scroll or click on load more then the other item will load
    Like Facebook feed or UA-cam feed

  • @ryzs_
    @ryzs_ 3 роки тому

    After many youtube videos I watch explaining about generator, this one most accurate! Finally i can move on 😂

  • @Kanexxable
    @Kanexxable 3 роки тому

    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

  • @rezaghaemifar5703
    @rezaghaemifar5703 Рік тому

    What a perfect explanation

  • @AnkurShah_CS
    @AnkurShah_CS 3 роки тому

    Should we use it in backend for creating id's ?? Any pros/cons ??

  • @johongirrahimov2343
    @johongirrahimov2343 3 роки тому +10

    That's how async await is implemented

    • @syedalimehdi-english
      @syedalimehdi-english 3 роки тому +3

      COOL
      I was thinking about promises for some reason while watching this and there you just made it clear. Thanks

    • @rkyshnan
      @rkyshnan 3 роки тому

      Thank you for highlighting this...

    • @igorswies5913
      @igorswies5913 3 роки тому +2

      aren't they implemented in C++?

  • @mishasawangwan6652
    @mishasawangwan6652 3 роки тому

    just a nitpit suggestion: if you turn up the ‘release’ parameter on your gate, the vocal audio would sound much smoother.