
When I started learning JavaScript, the first thing I did was compile a list of techniques that helped me save time. I peeped them from other programmers, on various sites and manuals.
In this article, I’ll show 12 great ways to improve and speed up your JavaScript code. In most cases, they are universal.
We remind: for all readers of "Habr" - a discount of 10,000 rubles when writing to any Skillbox course on the promotional code "Habr".
')
Skillbox recommends: Practical course "Mobile Developer PRO" .
Filtering Unique Values
MASSIFIES
The Set object type was introduced in ES6, along with ..., the spread operator, we can use it to create a new array that contains only unique values.
const array = [1, 1, 2, 3, 5, 5, 1] const uniqueArray = [...new Set(array)]; console.log(uniqueArray);
Normally, to perform the same operation, you need a lot more code.
This trick works for arrays containing primitive types: undefined, null, boolean, string, and number. If you are working with an array containing objects, functions, or additional arrays, you will need a different approach.
The length of the cache in cycles
CYCLES
When you study for for loops, you follow the standard procedure:
for (let i = 0; i < array.length; i++){ console.log(i); }
However, with this syntax, the for loop re-checks the length of the array at each iteration.
Sometimes this can be useful, but in most cases it is more efficient to cache the length of the array, which will require a single reference to it. We can do this by defining a variable length, where we set the variable i, for example, like this:
for (let i = 0, length = array.length; i < length; i++){ console.log(i); }
In principle, almost the same as above, but with an increase in the size of the cycle, we get a significant time saving.
Short Circuit Evaluation (McCarthy Evaluation)
CONDITIONAL OPERATORS
A ternary operator is a fast and efficient way to write simple (and sometimes not very simple) conditional statements:
x> 100? “More than 100”: “less than 100”;
x> 100? (x> 200? "more than 200": "between 100-200"): "less than 100";
But sometimes even the ternary operator is more complicated than required. Instead, we can use 'and' && and 'or' || logical operators for evaluating certain expressions in an even shorter way. It is often called a “short circuit” or “short circuit rating”.
How it worksLet's say we want to return only one of two or more conditions.
Using && returns the first false value. If each operand is evaluated as true, the last calculated expression will be returned.
let one = 1, two = 2, three = 3; console.log(one && two && three);
Using || will return the first true value. If each operand is evaluated as false, the last calculated value will be returned.
let one = 1, two = 2, three = 3; console.log(one || two || three);
Example 1Let's say we want to return a length variable, but do not know its type.
In this case, you can use if / else to check that foo is a suitable type, but this method may be too long. Therefore, we better take our "short circuit".
return (foo || []).length;
If the variable foo has a suitable length, then it will be returned. Otherwise, we get 0.
Example 2Did you have problems accessing the nested object? You may not know whether an object or one of its sub-properties exists, and this can lead to problems.
For example, we wanted to access the data property in this.state, but data is not defined until our program returns a sample request.
Depending on where we use it, calling this.state.data can prevent the application from starting. To solve the problem, we could wrap it in a conditional expression:
if (this.state.data) { return this.state.data; } else { return 'Fetching Data'; }
A more suitable option would be to use the “or” operator.
return (this.state.data || 'Fetching Data');
We cannot change the code above to use &&. The operator 'Fetching Data' && this.state.data returns this.state.data regardless of whether it is undefined or not.
Optional chainYou can suggest using an optional chain when trying to return a property deep into a tree structure. So, the question mark symbol? can be used to retrieve a property only if it is not null.
For example, we could refactor the example above by getting this.state.data? .. (). That is, data is returned only if the value is not null.
Or, if it’s important whether the state is defined or not, we could return this.state? .Data.
Convert to Boolean
TYPE TRANSFORMATION
In addition to the usual logical functions true and false, JavaScript also treats all other values ​​as truthy or falsy.
Until otherwise indicated, all values ​​in JavaScript are truthy, except for 0, "", null, undefined, NaN, and, of course, false. The latter are falsy.
We can easily switch between those and others using the! Operator, which also converts the type to logical.
const isTrue = !0; const isFalse = !1; const alsoFalse = !!0; console.log(isTrue);
Conversion to string
TYPE TRANSFORMATION
Fast conversion of an integer to a string can be performed as follows.
const val = 1 + ""; console.log(val);
Convert to integer
TYPE TRANSFORMATION
The inverse transform is done like this.
let int = "15"; int = +int; console.log(int);
This method can also be used to convert a boolean boolean data type to regular numeric values, as shown below:
console.log(+true);
There may be situations where + will be interpreted as a concatenation operator, not an addition. To avoid this, use the tilde: ~~. This statement is equivalent to -n-1. For example, ~ 15 is -16.
Using two tildes in a row negates the operation, because - (- - n - 1) - 1 = n + 1 - 1 = n. In other words, ~ -16 is equal to 15.
const int = ~~"15" console.log(int);
<Quick powers
OPERATIONS
Starting with ES7, you can use the exponentiation ** operator as a shorthand for degrees. This is much faster than using Math.pow (2, 3). It seems simple, but this moment is included in the list of receptions, because far from everywhere it is mentioned.
console.log(2 ** 3);
Do not confuse it with the ^ symbol, which is usually used for exponentiation. But in JavaScript it is an XOR operator.
Before ES7, the abbreviation ** could only be applied for a base 2 degree using the bitwise left shift operator <<:
Math.pow(2, n); 2 << (n - 1); 2**n;
For example, 2 << 3 = 16 is equivalent to the expression 2 ** 4 = 16.
Float to integer
OPERATIONS / TYPE TRANSFORMATIONS
If you need to convert a float to an integer, you can use Math.floor (), Math.ceil () or Math.round (). But there is a faster way, for this we use the |, that is, the OR operator.
console.log(23.9 | 0);
Behavior | largely depends on whether you are dealing with positive or negative numbers, so this method is only suitable if you are sure of what you are doing.
n | 0 removes everything that comes after the decimal separator, truncating a floating-point number to an integer.
You can get the same rounding effect using ~~. After a forced conversion to an integer, the value remains unchanged.
Remove the trailing numbersThe OR operator can be used to remove any number of digits from a number. This means that we do not need to convert types, like this:
let str = "1553"; Number(str.substring(0, str.length - 1));
Instead, simply prescribe:
console.log(1553 / 10 | 0)
Auto linking
CLASSES
The ES6 arrow notation can be used in class methods, and this implies a binding. Thanks to this, you can say goodbye to repeating expressions like this.myMethod = this.myMethod.bind (this)!
import React, { Component } from React; export default class App extends Compononent { constructor(props) { super(props); this.state = {}; } myMethod = () => {
Array trimming
MASSIFIES
If you need to remove values ​​from an array, then there are faster methods than splice ().
For example, if you know the size of the original array, you can override its length property as follows:
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; array.length = 4; console.log(array);
But there is another method, and more rapid. If speed matters to you, then here is our choice:
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; array = array.slice(0, 4); console.log(array);
Output the last value (s) of the array
MASSIFIES
This technique requires the use of the slice () method.
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(array.slice(-1));
JSON code formatting
Json
You may already have used JSON.stringify. Did you know that it helps format your JSON?
The stringify () method takes two optional parameters: the replacer function, which you can use to filter the displayed JSON, and the value space.
console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));
That's all, I hope that all these tricks were useful. And what tricks do you know? Write them in the comments.
Skillbox recommends: