JavaScript Shorthand Tricks Collection

Javascript shorthand tricks forms new convention which is able to help us reducing the amount of code we have to write. Also, short hand patterns are easier to read since a human can much more easily grasp the shorter code as a pattern. So code reading should be faster than normal. There will be more difficult to understand and maintain other developers’ code if you don’t know the shorthand.

1. Default assignments

Longhand:

Shorthand:

The variable will be set to the value of the left operand if it evaluates to true, therefore anything other than the following:

  • false
  • 0
  • null
  • undefined
  • empty string

Otherwise it will be set to the value of the right operand. So this isn’t the right thing to use if you need to explicitly set the length to zero.

2. Ternary operator (conditional)

Longhand:

Shorthand:

3. Associative array notation

Longhand:

Shorthand:

4. Variable increment/decrement/multiply/divide

Longhand:

Shorthand:

Or to add/subtract/multiply/divide a number to/from/by itself you can do:

Shorthand:

5. JavaScript for Loop & while Loop

Longhand:

Shorthand:

Longhand:

Shorthand:

6. Switch Cases statement

Longhand:

Shorthand:

7. Bitwise NOT Operator

bitwise NOT operator (~) : ~N equal -(N + 1)

double bitwise NOT operator (~~) : ~~N equal -(-(N + 1) + 1)

If the operand is a number and it’s not NaN or Infinity then ~~ will have the effect of rounding it towards zero (Math.ceil for negative, Math.floor for positive). If it’s not a number, then the internal ToInt32 function converts it to zero.

more resource about Bitwise Operators

8. Summary

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA