0

I'm a little baffled. For some reason this won't work:

[1, 2, 3].forEach(function(num) {
  console.log(num)
})

I get this error:

TypeError: Cannot call method 'forEach' of undefined

However, this will:

var nums = [1, 2, 3]

nums.forEach(function(num) {
  console.log(num)
})

Anyone have any idea what's going on here?

5
  • 1
    What version of Node are you running? It works for me. Commented Aug 29, 2014 at 18:39
  • The latest: v0.10.31 Commented Aug 29, 2014 at 18:40
  • What's the output of Array.prototype.forEach right before the first statement? Does it output a function? Commented Aug 29, 2014 at 18:43
  • It seems to be because I'm not using semicolons. Commented Aug 29, 2014 at 18:45
  • Oh, YEAH! It seems (at least in your fiddle) to be interpreting that you are setting your foo variable to [1,2,3]. var foo = 'bar' [1, 2, 3].forEach(function(num) { console.log(num) }) Commented Aug 29, 2014 at 18:51

2 Answers 2

1

So, it turns out it was because I'm not using semicolons, and the preceding code conflicted.

var foo = 'bar'

[1, 2, 3].forEach(function(num) {
  console.log(num)
})
Sign up to request clarification or add additional context in comments.

Comments

0

This is valid in both this jsbin: http://jsbin.com/kawatevovabu/1/edit

and in version v0.10.26 of node.js. Perhaps this is a platform issue?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.