title: ES5: Object.keys native method in JS
body: <p>I am using Object.keys to iterate through an object's keys in JS like so:</p>
  
  <pre><code>               var cv = view.childViews;
  
                  Object.keys(cv).forEach(function(key) {
                      this.destroyView(cv[key]);
                  }.bind(this));
  </code></pre>
  
  <p>however, when cv is undefined or is not an object, Object.keys throws an error. Instead of putting an if statement around Object.keys to check if the typeof cv is an object, is there a native method that is better than Object.keys in that it doesn't throw an error if cv is undefined?</p>
  
  <p>Isn't the whole point of:</p>
  
  <pre><code>Object.keys(cv) vs cv.keys().each()
  </code></pre>
  
  <p>if cv is null, the first shouldn't throw an error, whereas the latter should.
  What the heck, thanks JS.</p>
  
  <p>If you don't help me, I will being doing this, much to my own chagrin:</p>
  
  <pre><code>              if(typeof cv === 'object'){
                      Object.keys(cv).forEach(function(key) {
                          this.destroyView(cv[key]);
                      }.bind(this));
                  }
  </code></pre>
  
  <p>turns out, in ES6, non-object arguments to Object.keys will be "coerced" into an object, see:
  <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys</a></p>