Daniel Krom
Daniel Krom

Reputation: 10068

NodeJS [].forEach undefined

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

(Using NodeJs v5.4.1)

Have this code in a 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 property 'forEach' of undefined

It works if I'm changing the code to

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

I've tested the same function on Chrome.console and the first way works.
I know that both using V8 JS engine, is it a bug or something I'm missing with Javascript rules?

thanks!

Upvotes: 5

Views: 2319

Answers (1)

Andy
Andy

Reputation: 63589

Your code breaks if you don't have a semi-colon after this line:

var res = {}

To minimise these problems a good idea is to use a linter if you're not using one. 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 your workflow using Gulp or Grunt to catch these kind of errors before you commit code.

If you choose to omit semicolons where possible, my advice is to insert them immediately before the opening parenthesis or square bracket in any statement that begins with one of those tokens, or any which begins with one of the arithmetic operator tokens "/", "+", or "-" if you should happen to write such a statement. - blog entry by Michaeljohn Clement 2010

Upvotes: 4

Related Questions