21

Say I have either

msg = "Saved Successfully"

or

msg = -> "Saved #{@course.title} Successfully"

Is there anyway to elegantly get the value of msg without knowing whether it's a function or a regular variable rather than doing

success_message = if typeof msg is 'function' then msg() else msg

1 Answer 1

38

There's a CoffeeScript shorthand you can take advantage of:

f?()

is equivalent to

f() if typeof f is 'function'

which means that you can write

success_message = msg?() ? msg

This works because msg?() has the value undefined if msg isn't a function.

Caveat: This will fail if msg() returns null, setting success_message to the msg function.

Really, if you're going to do this in your application, you should write a utility function:

toVal = (x) -> if typeof x is 'function' then x() else x
successMessage = toVal msg

You could even attach toVal to the Object prototype if you're feeling adventurous..

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.