1

I am trying to write a FizzBuzz program with CoffeeScript like this:

array = [1..100]

console.log(array.forEach(
  (value)->
   if value%3 is 0 and value%5 is 0
    return "fizzbuz"
   if value%3 is 0
    return "fizz"
   if value%5 is 0
    return "buzz"
   value
   ))

And it keeps returning undefined. Why does this happen?

2 Answers 2

4

Since you're using CoffeeScript, simple for loops are expressions that result in arrays so you could say:

console.log(for value in array
    if value % 3 is 0 and value % 5 is 0
        "fizzbuz"
    else if value % 3 is 0
        "fizz"
    else if value % 5 is 0
        "buzz"
    else
        value
)

or if you really wanted to use a function, use do to create an SIF:

console.log(for value in array
    do (value) ->
        return 'fizzbuz' if value % 3 is 0 and value % 5 is 0
        return 'fizz'    if value % 3 is 0
        return 'buzz'    if value % 5 is 0
        return value
)

Demo: http://jsfiddle.net/ambiguous/ENLfx/

Sign up to request clarification or add additional context in comments.

Comments

4

The forEach array method doesn't return a resulting array. It executes a function once for each array element, and it doesn't return anything. If you want to return a resulting array, use map.

console.log(array.map(
  (value)->
    if value%3 is 0 and value%5 is 0
      return "fizzbuzz"
    if value%3 is 0
      return "fizz"
    if value%5 is 0
      return "buzz"
    value
  ))

FIDDLE

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.