20

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

5 Answers 5

19

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'.

Sign up to request clarification or add additional context in comments.

1 Comment

This is my favorite answer, but I wonder if using ; would be (a very tiny bit) more efficient than null?
17

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.

Comments

8

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

Comments

6

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.

Comments

1

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;

1 Comment

this works well with switch statements, but doesn't fully fill in for pass because it can't be used in an if/else like pass can.

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.