Câu hỏi phỏng vấn Javascript
Câu hỏi

What is generator in JS?

Câu trả lời

A generator in JavaScript is a special type of function that can pause its execution and later resume from where it left off. This capability is facilitated by the yield keyword, which is used within the generator function to pause execution and return a value to the caller. When the generator function is resumed, it picks up right after the last yield statement that was executed.

Generators are defined using the function* syntax, which distinguishes them from regular functions. Here's a basic example of a generator function:

javascript Copy
function* simpleGenerator() {
    yield 'First yield';
    yield 'Second yield';
    return 'Generator done';
}

When this generator function is called, it returns a Generator object but does not execute any of its code immediately. Instead, the code executes in segments, each segment ending at a yield statement. The next() method is used on the Generator object to resume execution and move from one yield to the next. Each call to next() returns an object with two properties: value, which is the result of the yield expression, and done, which is a boolean indicating whether the generator function has finished executing.

Generators are particularly useful for managing asynchronous operations and complex control flows in a more readable and maintainable way. They allow functions to avoid running to completion immediately, enabling them to handle tasks like iterating over data streams or managing asynchronous interactions without the callback hell or complexity introduced by Promises alone[1][2][3][5][6][12].

Generators also maintain their internal state between executions, maki...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What is a closure, and how/why would you use one?

junior

Explain event bubbling and how one may prevent it

middle

What is the drawback of creating true private in JavaScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào