Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operation in CoffeeScript

I need to set value to a that depends on a condition.

What is the shortest way to do this with CoffeeScript?

E.g. this is how I'd do it in JavaScript:

a = true  ? 5 : 10  # => a = 5 a = false ? 5 : 10  # => a = 10 
like image 620
evfwcqcg Avatar asked Apr 13 '12 18:04

evfwcqcg


People also ask

What can you do with CoffeeScript?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.

How do you write a CoffeeScript?

Single-line Comments. Whenever we want to comment a single line in CoffeeScript, we just need to place a hash tag before it as shown below. Every single line that follows a hash tag (#) is considered as a comment by the CoffeeScript compiler and it compiles the rest of the code in the given file except the comments.

Is CoffeeScript like JavaScript?

One crucial difference between the two languages is that TypeScript is the superset of JavaScript while CoffeeScript is a language which is an enhanced version of JavaScript. Not just these two languages but there are other languages such as Dart, Kotlin, etc. which can be compiled into JavaScript.


2 Answers

Since everything is an expression, and thus results in a value, you can just use if/else.

a = if true then 5 else 10 a = if false then 5 else 10 

You can see more about expression examples here.

like image 96
loganfsmyth Avatar answered Sep 19 '22 15:09

loganfsmyth


a = if true then 5 else 10 a = if false then 5 else 10  

See documentation.

like image 20
Paul Oliver Avatar answered Sep 16 '22 15:09

Paul Oliver