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!
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.
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With