Skip to content

Instantly share code, notes, and snippets.

@korokd
Created July 19, 2019 18:40
Show Gist options
  • Save korokd/261f47919cb5454b10be3fe443ad50b8 to your computer and use it in GitHub Desktop.
Save korokd/261f47919cb5454b10be3fe443ad50b8 to your computer and use it in GitHub Desktop.
JS heuristics (?) I discover along my way

Title

Things will be explained by examples, since this gist is primarily for myself :P

Short circuit

JavaScript short circuits Comparison Operators. Hence, you may be able to gain performance (?) by using them with this in mind.

AND

If variable a has 70% chance of being truthy and variable b has 50% chance of being truthy, you might prefer to write your if statement as if (b && a) {...} than if (a && b) {...}. Why? Because with the first, 50% of the time the engine will not even have to check for a's value neither coerce it into a boolean, while with the latter, it will be able to skip so only 30% of the time.

OR

As opposed to the AND, here you prefer to check for the variable with more probability of being truthy first, since it will cause the short circuit more often. Yes, you got it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment