1

I'm looking at the following example from CoffeeScript: Accelerated Development

x = true
showAnswer = (x = x) ->
  console.log if x then 'It works!' else 'Nope.'

console.log "showAnswer()", showAnswer()
console.log "showAnswer(true)", showAnswer(true)
console.log "showAnswer(false)", showAnswer(false)

I don't understand why showAnswer(...) undefined shows up for each test.

Nope.
showAnswer() undefined
It works!
showAnswer(true) undefined
Nope.
showAnswer(false) undefined

Please explain the output of each case.

1
  • As a side note, you don't need to define x = true prior to your function if you want to give it a default value. (x = true) -> is a valid (and I think preferred) method signature. Commented May 20, 2014 at 15:39

1 Answer 1

4

Don't forget that CoffeeScript, by default, returns the last statement in a function. So what your showAnswer function actually says is:

showAnswer = (x = x) ->
    return console.log if x then 'It works!' else 'Nope.'

or compiled to JavaScript:

showAnswer = function(x) {
  if (x == null) {
    x = x;
  }
  return console.log(x ? 'It works!' : 'Nope.');
};

The other thing to realize is that the console.log method returns undefined. So when you log the result of your showAnswer method, it will print undefined.

If I understand your intention correctly, I would modify your original function to do this:

showAnswer = (x = x) ->
  if x then 'It works!' else 'Nope.'

Alternatively, modify your console.log statements as such:

console.log "showAnswer()"
showAnswer()

console.log "showAnswer(true)"
showAnswer(true)

console.log "showAnswer(false)"
showAnswer(false)
Sign up to request clarification or add additional context in comments.

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.