Last Updated: February 25, 2016
·
807
· ericanderson

Safely short circuiting a function

Often in code, you will see this pattern:

if (simpleTest) {
  doSomething();
  return;
}

However, often you would like your code concise. You could do this:

if (simpleTest) { doSomething(); return; }

But now you need to add curly braces (not that this generally matters). However you could also use this syntax:

if (simpleTest) return void doSomething();

This will execute doSomething() but will return undefined, so that you don't have to expose the internal state returned by doSomething() to your caller.

1 Response
Add your response

This is a cool trick! Thanks

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside