Alice
Alice

Reputation: 909

How to return object explicitly in CoffeeScript

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?

Upvotes: 46

Views: 22335

Answers (4)

alsotang
alsotang

Reputation: 1605

I think the best way is

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

because it fits the philosophy of functional programming.

Upvotes: 2

Tim Scott
Tim Scott

Reputation: 15205

The previous answers are all correct. This works too:

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

Upvotes: 1

matyr
matyr

Reputation: 5774

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

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

myFunc = ->
  # return
  id   : 3
  name : 'myname'

Upvotes: 92

Adrien
Adrien

Reputation: 9531

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'
  )

Upvotes: 10

Related Questions