Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS [].forEach undefined

Tags:

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!

like image 416
Daniel Krom Avatar asked May 07 '16 11:05

Daniel Krom


People also ask

Why is my forEach undefined?

The "Cannot read property 'forEach' of undefined" error occurs when calling the forEach method on an undefined value. To solve the error make sure to initialize the variable to the correct value and only call the forEach method on the correct data type.

Why does calling forEach on an array return undefined?

Because forEach does not create a new object. It doesn't have a return value. You could simply return testArray; since you are mutating that object. Of course you can't return from forEach .

Does forEach always return undefined?

forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

What can I use instead of forEach?

The every() function is a good alternative to forEach, let us see an example with a test implementation, and then let's return out of the every() function when a certain condition meet.


1 Answers

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

like image 117
Andy Avatar answered Sep 28 '22 03:09

Andy