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)?
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.
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.
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.
The yield* expression is used to delegate to another generator or iterable object.
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;
}
})();
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With