Andrew
Andrew

Reputation: 43153

CoffeeScript: simplest way to check if a function returns data

I have a function like this:

getData = ->
  $('body').data('key')

I have another function that I want to use the first function to check if there's some data. What I want to write is this:

otherFunction = ->
  if getData()
    ...do something...

However, in my testing the statement if function() will always be true, because there's something there (a function). So the above doesn't work.

What's the cleanest way to do what I'm attempting here, check that a function returns some data?

Upvotes: 1

Views: 294

Answers (2)

Matthew Blancarte
Matthew Blancarte

Reputation: 8301

Your pattern will definitely resolve to false (because of a falsy return value) if there is no data attribute, or there is an empty data attribute on a dom element.

See this example: http://jsfiddle.net/wkGcW/1/

getData = ->
  $('div').data 'key'

getData2 = ->
  $('div').data 'foo', 'bar'

otherFunction = ->
  if getData()
    console.log 'yep'
  else
    console.log 'nope'  <--- Resolves false

  if getData2()
    console.log 'yep'   <--- Resolves true
  else
    console.log 'nope'

otherFunction()

You may have some other issue at play...

Upvotes: 3

elzaer
elzaer

Reputation: 729

something like:

if(getData() !== false) then do...

you would need to have a return escape on your getData method.

Is get data an object or a method returning data?

Upvotes: 0

Related Questions