1. Passing arguments as objects
Instead of passing parameters in a specific order, you can pass them as an object. This approach improves the readability of your code and makes it easier to manage. Using this technique eliminates the need to repeatedly check the function definition, and auto-completion becomes easier. It also helps to communicate the function's intent more clearly as function calls specify the value of each property.
2. Use the optional chaining operator
The optional chaining operator makes it easier to compare against undefined values. It allows you to use expressions with bracket notation and to stack optional chaining operators to check for deeper properties. This operator helps to improve code readability and makes it less prone to errors.
3. Using generators to create sequential IDs
Generators are functions that employ lazy evaluation by making use of the yield keyword to process and return data, on demand. It may look like generator functions will burn CPU cycles in an infinite loop; however, generators describe a state machine, allowing transitions to forward states to occur through provided code. These transitions occur on-demand whenever the next method is called, hence the term lazy evaluation. One practical use of generators is to create sequential IDs.
4. Use the spread operator to shallow copy objects
The spread operator is a one-liner that helps to concatenate arrays or merge objects instead of iterating over each instance manually. It is especially useful when performing state management in React or React Native.
5. Remove duplicates from arraysusing Set
6. Casting values in arrays using map
7. Time the execution of your code
The time method takes a timer name as a parameter and expects to be met with a call to timeEnd, in which the same timer name is supplied. The timeEnd method prints the elapsed time in milliseconds between the two function calls.
8. Truncate an array using length
Truncating an array is easy by specifying the desired length. The array will be truncated with the sequence of that specific length that you set.
9. Use a switch/case statement instead of a series of if/else
Using a switch/case statement is faster when there are more than two cases, and it is more elegant. Avoid using it when you have more than ten cases.
10. Convert to floating number without killing performance
To convert a value to a floating number without killing performance, instead of using math.floor, math.ceil, and math.round, use "~~" to eliminate decimals.
11. Use Array Filter
This trick helps to filter out a bucket of elements from an array pool. This method creates an array filled with all array elements that pass a test provided as a function. According to the requirement, create a callback function for non-required elements.
12. Use a code beautifier
13. Cache your variables