In Python one can use the 'pass' statement to do nothing:
if true:
pass
Is there a similar statement in coffeescript? I'm trying to do a switch statement and do nothing if certain conditions are met.
switch variable:
when 5 then pass
else do variable
Python's pass mainly exists because in Python whitespace matters within a block. In Javascript, the equivalent would be putting nothing within the block, i.e. {} .
In Python, the pass keyword is an entire statement in itself. This statement doesn't do anything: it's discarded during the byte-compile phase. But for a statement that does nothing, the Python pass statement is surprisingly useful. Sometimes pass is useful in the final code that runs in production.
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.
In general, we use parenthesis while declaring the function, calling it, and also to separate the code blocks to avoid ambiguity. In CoffeeScript, there is no need to use parentheses, and while creating functions, we use an arrow mark (->) instead of parentheses as shown below.
i'm a happy user of
switch x
when 1
null
when 2
y = 3
else
y = 4
since null
is already in the language and does semantically transport that meaning of 'nothing'.
Unlike in Python, empty blocks are (usually) valid in CoffeeScript. So you can simply use:
switch variable:
when 5 then
else
variable
Note that without the then
it won't compile, which I find a bit odd. This works pretty generally, though:
if x
else if y
something()
else
somethingElse()
is perfectly valid CoffeeScript.
Because every expression has a value in CoffeeScript, a pass
keyword, if it existed, would be equivalent to the value undefined
. So, you could define
pass = undefined
and then use pass
just like in Python:
switch variable
when 5
pass
else
do variable
I always use a semicolon for this:
switch variable
when 5 then ;
else do variable
This is because in javascript, a semicolon is a valid statement which also happens to do nothing.
Update: I just thought of another interesting way of doing this. You could define pass
as a global variable and set it to undefined
:
window.pass = undefined
switch variable
when 5 then pass
else do variable
The only thing you have to watch out for is using pass
as a local variable or redefining the global pass
variable. That would break your code.
If you use Google's closure compiler, you could annotate this variable so that it is a constant:
`/** @const */ var pass;`
But then it would have to go at the beginning of each file. You could write your own preprocessor to do that automatically, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With