title: How to identify an ES6 generator
body: <p>Say I've got a generator function like this:</p>
  
  <pre><code>var g = function*() {
    yield 1;
    yield 2;
    yield 3;
  };
  
  var gen = g();
  </code></pre>
  
  <p>How can I tell programmatically that <code>g</code> is a generator function, or that <code>gen</code> is an iterator?</p>
  
  <p>This seems like one possibility:</p>
  
  <pre><code>g.constructor.name === 'GeneratorFunction'
  </code></pre>
  
  <p>Is there a better way?</p>
  
  <p><strong>Update</strong>: I ended up <a href="https://github.com/dtao/lazy.js/blob/5e252f3779413743aa6eb15fe5f5f1062884ef3b/lazy.js#L5729-L5752" rel="nofollow noreferrer">taking an approach</a> similar to <a href="https://stackoverflow.com/a/21559723/105570">Eric's answer</a>, but using <code>eval</code> to first determine whether generators are supported on the target platform in the first place. Here is the implementation:</p>
  
  <pre><code>var GeneratorConstructor = (function() {
    try {
      var generator;
      return eval('generator = function*() { yield 1; };').constructor;
  
    } catch (e) {
      // If the above throws a SyntaxError, that means generators aren't
      // supported on the current platform, which means isGenerator should
      // always return false. So we'll return an anonymous function here, so
      // that instanceof checks will always return false.
      return function() {};
    }
  }());
  
  /**
   * Checks whether a function is an ES6 Harmony generator.
   *
   * @private
   * @param {Function} fn
   * @returns {boolean}
   */
  function isGenerator(fn) {
    return fn instanceof GeneratorConstructor;
  }
  </code></pre>