1.

Implement your version of Array.prototype methods some, every and reduce in vanilla JavaScript ?

Answer»

ES6 introduced a new way of WORKING with functions and iterators in the form of Generators (or generator functions). A generator is a function that can stop midway and then continue from where it stopped.  

Let’s look at the below EXAMPLE. The generator function have a special syntax with “*”. Also, INSIDE the generator we have “yield” statements. Each “next()”, goes to the next yield statement.

The above example doesn’t shows any advantages of generator and it is same as iterating through an array. But let’s look at next example, where we have an infinite while loop inside an generator.
First look at this normal function. If we run it, it will cause an infinite loop and crash your browser.

But the same type of function with generator doesn’t produce an infinite loop. It pauses every time yield is called and will generator the next value of “i” every-time “next()” is called. So, this function can be USED to GENERATE any time “i” and not like in array where we have to give the size of array in advance.



Discussion

No Comment Found