The shorthand techniques of any programming language help you to write more clean and optimized code and lets you achieve your goal with less coding. Let’s discuss some of the shorthand techniques of JavaScript one by one.
1. Declaring variables
2. Assigning values to multiple variables
We can assign values to multiple variables in one line with array destructuring.
3. The Ternary operator
We can save 5 lines of code here with ternary (conditional) operator.
4. Assigning default value
We can use OR(||) short circuit evaluation to assign a default value to a variable in case the expected value found falsy.
5. AND(&&) Short circuit evaluation
If you are calling a function only if a variable is true, then you can use AND(&&) short circuit as an alternative for this.
The AND(&&) short circuit shorthand is more useful in React when you want to conditionally render a component. For example:
6. Swap two variables
To swap two variables, we often use a third variable. We can swap two variables easily with array destructuring assignment.
7. Arrow Function
8. Template Literals
We normally use + operator to concatenate string values with variables. With ES6 template literals we can do it in a more simple way.
9. Multi-line String
For multiline string we normally use + operator with a new line escape sequence (\n). We can do it in an easier way by using backticks (`).
10. Multiple condition checking
For multiple value matching, we can put all values in array and use indexOf() or includes() method.
11. Object Property Assignment
If the variable name and object key name is same then we can just mention variable name in object literals instead of both key and value. JavaScript will automatically set the key same as variable name and assign the value as variable value.
12. String into a Number
There are built in methods like parseInt and parseFloat available to convert a string to number. We can also do this by simply providing a unary operator (+) in front of string value.
13. Repeat a string for multiple times
To repeat a string for a specified number of time you can use a for loop. But using the repeat() method we can do it in a single line.
14. Exponent Power
We can use Math.pow() method to find the power of a number. There is a shorter syntax to do it with double asterik (**).
15. Double NOT bitwise operator (~~)
The double NOT bitwise operator is a substitute for Math.floor() method.
Some of these shorthand techniques may seem inappropriate to use in a project, but it's a good idea to know some additional techniques. Happy coding and have a nice day!
Top comments (0)