TECHY360
Everything You Need To Know About Tech
0 92

When I started learning JavaScript, I compiled a list of tricks that I found in someone else’s code, on code checking websites, and anywhere else except for the tutorials I used.

Since then I have been adding to this list, and in this article, I will share 12 tips that seem to be especially smart or useful.

Although many of these tricks are convenient in any context, some of them are hardly suitable for the production level, where clarity is often more important than brevity.

So, here are 12 elegant ways to write a more concise and productive code.

## 1. The filter of unique values

ARRAYS

The Set type was introduced in ES6, and along with the spread operator, `...` we can use it to create a new array with unique values.

```const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
```

Prior to ES6, filtering unique values ​​would require much more code than now!

This trick works for arrays containing primitive types: undefined, null, boolean, string and number. (If you had an array containing objects, functions, or additional arrays, you would need a different approach!)

## 2. We cache array length in cycles

CYCLES

When we are taught for loops, we are advised to follow this standard structure:

```for (let i = 0; i < array.length; i++){
console.log(i);
}
```

However, using this syntax, the for loop revises the length of the array at each iteration.

Sometimes this can be useful, but in most cases it is better and more efficient to cache the length of the array, so you need to access it only 1 time. We can do this by defining a variable`length`

```for (let i = 0, length = array.length; i < length; i++){
console.log(i);
}
```

This code is almost as concise as the one above, but it works in such a way that when we increase the size of the array, we don’t waste time re-checking `array.length`.

## 3. Short circuit calculation

CONDITIONAL OPERATORS

A ternary operator is a quick way to write simple (and sometimes not very simple) conditional constructions, for example:

```x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';
```

But sometimes even the ternary operator is more complicated than necessary. Instead, we can use the logical operators “and” && and “or” || for a more accurate assessment of certain expressions. It is often called a “short circuit”.

### How it works

Suppose we want to return only one of two or more options.

Using && will return the first `false`or `‘ложноe’`value. If each operand evaluates to true, the last expression evaluated will be returned.

```let one = 1, two = 2, three = 3;
console.log(one &amp;&amp; two &amp;&amp; three); // Result: 3
console.log(0 &amp;&amp; null); // Result: 0
```

Using || will return the first `true`or `‘правдивоe’`value. If each operand evaluates to false, the last expression evaluated will be returned.

```let one = 1, two = 2, three = 3;
console.log(one || two || three); // Result: 1
console.log(0 || null); // Result: null
```

### Example 1

Suppose we want to return a property of a `length`variable, but we do not know its type.

We can use the operator `if/else`operator to verify that foo is an acceptable type, however it can take quite a while. Short circuit allows you to do it this way:

```    return (foo || []).length;
```

If the variable foo has a length property, it will be returned. Otherwise, the length of the empty array will be returned: 0.

### Example 2

Have you had problems accessing a nested object? You may not know if an object has a property or one of the sub-properties, and this can cause unpleasant errors.

Suppose we wanted to access a property `data`that is inside `this.state`, but data is undefined until the program returns a response.

Depending on where we use this code, a call `this.state.data`may interfere with the launch of our application. To get around this, we could wrap everything in a conditional expression:

```if (this.state.data) {
return this.state.data;
} else {
return 'Fetching Data';
}
```

That seems pretty boring. The “or” operator provides a more concise solution:

```return (this.state.data || 'Fetching Data');
```

We cannot change the code above to use &&. The statement `'Fetching Data' && this.state.data`will be returned `this.state.data`whether it is equal `undefined`or not. This is because the ‘Fetching Data’ is “true” and therefore && will always skip it when it is listed first.

### New Feature Offered: Optional Sequence

Currently, there is a proposal to allow an “optional sequence” when trying to return a property that is deep in the tree structure. According to the sentence, a question mark symbol? can be used to retrieve a property only if it is not`null`

For example, we could give our example above to `this.state.data?.()`– will return data only if it is not `null` .

Or, if we doubt the variable `state`, we could return `this.state?.data`.

The proposal is currently on Stage 1 as an experimental feature. You can read about it here , and you can use it in your JavaScript via Babel by adding @ babel / plugin-proposal-optional-chaining to your .babelrc file.

## 4. Convert to Boolean

CAST

Besides the usual boolean values ​​true and false, JavaScript also treats all other values ​​as “true” or “false”.

Unless otherwise specified, all values ​​in JavaScript are “true” except `0, "", null, undefined, NaN`and, of course `false` , which are “falsy”.

We can easily switch between true and false using the negative operator!, Which also converts the type to “boolean”.

Related Posts
1 of 26
```const isTrue  = !0;
const isFalse = !1;
const alsoFalse = !!0;

```

This type of type conversion can be useful in conditional expressions, although the only reason you would decide to define false as! 1 is if you were playing code golf !

## 5. Convert to String

CAST

To quickly convert a number to a string, we can use the + concatenation operator, followed by an empty quote set “”.

```const val = 1 + "";
console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"

```

## 6. Convert to Number

CAST

The converse can be done quickly with the addition operator +.

```let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

```

It can also be used to convert boolean to numbers, as shown below:

```console.log(+true);  // Return: 1
console.log(+false); // Return: 0

```

There may be contexts in which the + operator will be interpreted as a concatenation operator, and not as an addition operator. In such a case (you want to return an integer, not a floating-point), you can use tildes: ~~.

The tilde, known as the “bitwise NOT operator,” is the operator equivalent to -n – 1. So, 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 15.

```const int = ~~"15"
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

```

Although I cannot come up with many use cases, the bitwise NOT operator can also be used in booleans: ~ true = -2 and ~ false = -1.

## 7. Fast exponentiation

OPERATIONS

Starting with ES7, it became possible to use the exponentiation operator ** as an abbreviation for degrees, which is faster than the Math.pow entry (2, 3). This is simple material, but it got on the list because there aren’t many training courses this operator contains!

```console.log(2 ** 3); // Result: 8
```

It should not be confused with the ^ character, usually used to record exponents, because in JavaScript it is a bitwise XOR operator.

Prior to ES7, a reduction existed only for degrees with base 2 using the bitwise left shift operator <<:

```    // The following expressions are equivalent:
Math.pow(2, n);
2 << (n - 1);
2**n;
```

For example, 2 << 3 = 16 is equivalent to 2 ** 4 = 16.

## 8. Fast Convert Float to Integer

OPERATIONS / TYPING

If you want to convert a floating-point number to an integer, you can use Math.floor (), Math.ceil (), or Math.round (). But there is also a faster way to crop a floating-point number to an integer using | bitwise OR operator.

```console.log(23.9 | 0);  // Result: 23
console.log(-23.9 | 0); // Result: -23

```

Behavior | depends on whether you are dealing with positive or negative numbers, so it is better to use it, you are sure of the operands.

If n is positive, n | 0 is rounded up. If n is negative, it is rounded down. To put it more precisely, this operation removes everything that follows the decimal point, truncating the floating-point number to an integer.

You can get the same effect using ~~ as described above, and virtually any bitwise operator will result in a float to an integer. The reason why these specific operations work is because, after forced conversion to an integer, the value remains unchanged.

### Delete last digits

The bitwise OR operator can also be used to remove any number of digits from the end of an integer. This means that we do not need to use similar code to convert between types:

```let str = "1553";
Number(str.substring(0, str.length - 1));
```

Instead, the bitwise OR operator allows us to do this:

```console.log(1553 / 10   | 0)  // Result: 155
console.log(1553 / 100  | 0)  // Result: 15
console.log(1553 / 1000 | 0)  // Result: 1
```

## 9. Automatic binding in classes

CLASSES

We can use ES6 arrow notation in class methods, and binding is implied. This saves a few lines of code in our class constructor, and we can happily say goodbye to duplicate expressions such as
this.myMethod = this.myMethod.bind (this)!

```import React, { Component } from React;
export default class App extends Compononent {
constructor(props) {
super(props);
this.state = {};
}
myMethod = () => {
// This method is bound implicitly!
}
render() {
return (
<>
<div>
{this.myMethod()}
</div>
</>
)
}
};
```

## 10. Array trimming

ARRAYS

If you want to remove values ​​from the end of an array destructively, there are faster alternatives than using splice ().

For example, if you know the size of your source 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); // Result: [0, 1, 2, 3]
```

This is a particularly concise solution. However, I have found the run-time of the slice () method to be even faster. If speed is your main goal, consider using something like this:

This is a particularly concise solution. However, I found that the execution time of the slice () method is even faster. If your main goal is speed, think about it:

```let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);
console.log(array); // Result: [0, 1, 2, 3]
```

## 11. Get the n last elements of the array

ARRAYS

The slice () array method can take negative integers, and if present, it will take values ​​from the end of the array, not from the beginning.

```let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(array.slice(-1)); // Result: 
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]
```

## 12. Formatting JSON code

JSON

Lastly, you may have used JSON. Stringify before, but did you realize it can also help indent your JSON for you?

You may have used JSON.stringify before, but did you know that you can indent your JSON?

The stringify () method takes two additional parameters: the replacer function, which you can use to filter JSON, and the space value.

The value space takes an integer for the number of spaces or a string (for example, ‘\ t’ to insert tabs), which can make it easier for you to read JSON.

```    console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));
// Result:
// '{
//     "alpha": A,
//     "beta": B
// }'

```

All in all, I hope you found these tips as useful as I did when I first discovered them.