46

This works:

myfunc = () ->
    id: 3
    name: 'myname'

But I want to be explicit about returning object.

myfunc = () ->
    return
        id: 3
        name: 'myname'

But I get "Unexpected 'INDENT'" error. What's wrong with the above code?

Alice
  • 909
  • 1
  • 11
  • 15
  • 1
    See https://github.com/jashkenas/coffee-script/issues/1263. – Jakub Hampl Dec 21 '11 at 09:27
  • 2
    you’re better off not to explicitly return it, as coffeescript always implictitly returns stuff. explicitly doing it is not only redundant, but might trick the reader into believing it makes a difference and functions without explicit return value would return `undefined` like in JS. – flying sheep Jan 13 '13 at 22:24
  • @flyingsheep "not only redundant, but might trick the reader into believing it makes a difference" That is such a critical point and is applicable to so many different. – Joshua Pinter Jan 08 '15 at 19:48
  • You shouldn't assume everyone is an idiot. Experienced CoffeeScript users often use explicit return statements. Personally, I only use implicit returns with functions that have a single expression as their body, which is a popular approach. Not using a language feature because you assume people will be confused by something this basic is a recipe for some truly awful code. – Carl Smith Oct 09 '17 at 14:45

4 Answers4

92
myFunc = ->
  return {
    id   : 3
    name : 'myname'
  }

myFunc = ->
  return {} =
    id   : 3
    name : 'myname'

myFunc = ->
  # return
  id   : 3
  name : 'myname'
matyr
  • 5,774
  • 28
  • 22
10

you should put the return value on the same line or wrap it in () :

myFunc = () ->
  return id:3, name:'myname'

myFunc = () ->
  return (
    id: 3
    name: 'myname'
  )
Adrien
  • 9,551
  • 3
  • 26
  • 27
2

I think the best way is

myFunc = ->
  return (
    id: 3
    name: 'myname'
  )

because it fits the philosophy of functional programming.

alsotang
  • 1,520
  • 1
  • 13
  • 15
1

The previous answers are all correct. This works too:

myFunc = () -> 
    {
        id: 3
        name: 'myname'
    }
Tim Scott
  • 15,106
  • 9
  • 65
  • 79