Reputation: 1087
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
Upvotes: 20
Views: 3968
Reputation: 997
This makes sense to me in coffeescript:
switch variable
when "a" then doSomething()
when "b" then break
This compiles to the following js:
switch (variable) {
case "a":
doSomething();
break;
case "b":
break;
}
Note: You shouldn't use null like @flow suggests, because it inserts an unnecessary statement like this
null;
Upvotes: 1
Reputation: 3652
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'.
Upvotes: 19
Reputation: 17505
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.
Upvotes: 17
Reputation: 77416
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
Upvotes: 8
Reputation: 5711
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.
Upvotes: 6