NodeJS [] .forEach undefined

I have a strange problem with [].forEach in NodeJS.

(Using NodeJs v5.4.1)

Enter this code in the function

 function _buildUserQuestionsForDisplay(question,callback){ var res = {} ["is_open","created","deleted","_id"].forEach(function(v){ res[v] = question[v] }) ... ... } 

Throwing an error:

["is_open", "created", "deleted", "_ ID"]. Foreach (function (v) {

TypeError: cannot read 'forEach' property from undefined

It works if I change the code to

 var arr = ["is_open","created","deleted","_id"]; arr.forEach(function(v){ res[v] = question[v] }) 

I tested the same function on Chrome.console and the first method works.
I know that both using the V8 JS engine, is this a bug or something that I am missing with Javascript rules?

thanks!

+5
source share
1 answer

Your code breaks if after this line you do not have a half-colony:

 var res = {} 

To minimize these problems, a good idea is to use linter if you are not using it. Both JSHint and ESLint can be added as dev plugins to your code editor (I use ESLint with the Airbnb stylesheet in SubmlimeText), and can also be added to the workflow using Gulp or Grunt to catch these errors before committing the code.

If you prefer to omit semicolons, if possible, my advice is to insert them immediately before the opening bracket or square bracket in any statement that starts with one of these tokens, or any that starts with one of arithmetic tokens of the operator "/", "+" or "-", if you must write such an expression. - blog entry Michaeljohn Clement 2010

+3
source

All Articles