Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript check yield support

I read about the yield keyword in JavaScript and I need to use it in my project. I read that this keyword has been implemented starting from a certain version of JS so I think that old browsers don't support it (right?).

Is there a way to check if the yield keyword is supported? or at least is there a way to check if the version of JS is greater or equal than the one that implements that keyword (1.7)?

like image 495
mck89 Avatar asked Feb 19 '10 15:02

mck89


People also ask

What is Yield * JavaScript?

The yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword. yield can only be called directly from the generator function that contains it.

How does yield work JS?

In JavaScript, yield is used to pause the execution of a function. When the function is invoked again, the execution continues from the last yield statement. A generator returns a generator object, which is an iterator. This object generates one value at a time and then pauses execution.

What is @yield used for?

Yield is a keyword in Python that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Any function that contains a yield keyword is termed a generator. Hence, yield is what makes a generator.

What is yield delegation in JavaScript?

The yield* expression is used to delegate to another generator or iterable object.


2 Answers

Here's a function for checking if yield can be used.

var can_yield = (function(){ 
    try { 
        return eval("!!Function('yield true;')().next()"); 
    } 
    catch(e) { 
        return false; 
    } 
})();
like image 142
Tymon Sturgeon Avatar answered Oct 10 '22 08:10

Tymon Sturgeon


yield introduces new syntax to JavaScript. You won't be able to use yield unless you have specified that you want the new JavaScript syntax, by including a version number in the script type attribute(*).

When you specify a script version, only browsers that support the given version will execute the block at all. So only Firefox, and not IE, Opera or WebKit, will execute the top block in:

<script type="text/javascript;version=1.7">
    function x() {
        yield 0;
    }
    var canyield= true;
</script>
<script type="text/javascript">
    if (!window.canyield) {
        // do some fallback for other browsers
    }
</script>

(*: note that the type and version specified in the type attribute exclusively determines whether external scripts are fetched, executed, and the mode for the execution. The Content-Type of a script is, unfortunately, completely ignored.)

like image 14
bobince Avatar answered Oct 10 '22 09:10

bobince