12 JavaScript tricks that you’ll never find in most tutorials


When I started to learn Javascript, I made a list of all the tricks, useful for saving time, which I found in the code of other people, in the various web code sharing on programming sites, such as stack overflow at any other place different from the tutorial I was using.
di Antonio Lamorgese


When I started to learn Javascript, I made a list of all the tricks, useful for saving time, which I found in the code of other people, in the various web code sharing on programming sites, such as stack overflow at any  other  place  different from the  tutorial I was using.

Since then I have contributed to this list and, in this article, I will share 11 tips chosen at hand seem particularly intelligent or useful. This post is intended to be useful for the beginner, but I hope that the intermediate JavaScript developers will find something new in this list.

While many of these tips are useful in any context, some may be better suited to the course code than the production-level code, where clarity is often more important than brevity; I’ll let you be the judge of that!

So, in no particular order, here are 11 ways to write code more concise and more efficient.

1. Filter unique values

ARRAYS

The  Set(object type) was introduced in ES6 and, together with  ...the operator ‘spread’, we can use it to create a new array with  only  unique values.

const array = [1, 1, 2, 3, 5, 5, 1] 
const uniqueArray = [... new set (array)]; console.log (uniqueArray); 
// Result: [1, 2, 3, 5]

Before ES6, isolate unique values ​​would mean a lot more code than that!

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

2. Short circuit rating

CONDITIONAL

The ternary operator is a quick way to write simple conditional statements (and sometimes not so simple), like these:

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 logical operators ‘AND’  && and ‘OR’  ||to evaluate certain expressions in a more concise way. This is often called “short” or “short circuit evaluation.”

How does it work

Let’s say we want to return only one of two or more options.

using  && return the first  false or “false” If each operand value is evaluated  true, it will be returned the last expression evaluated.

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

Using  ||return the first  trueor “truth” value. If each operand is evaluated  false, it will be returned the last expression evaluated.

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

Example 1

Let’s say we want to return  lengthto a variable, but do not know the type of variable.

We could use  if/elsean instruction to verify that  fooit is an acceptable type but this could be quite forward-looking. The short circuit rating, we instead of doing this:

 return (foo || []).length; 

If the variable  foois true, it will be returned. Otherwise, the  lengtharray will be returned empty:  0.

Example 2

Have you ever had problems of access to a nested object property? You may not know if there is an object or sub-properties and this can cause frustrating errors.

Suppose you want to access a property called  datain  this.state, but  datais not defined until our program has not returned properly a retrieval request.

Depending on where we use, the call  this.state.datacould prevent the execution of our app. To work around this, we could wrap it in a conditional:

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

But it seems quite repetitive. The ‘or’ operator provides a more concise solution:

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

We can not refactificare the above code to use it  &&. The declaration  'Fetching Data' && this.state.datawill return  this.state.dataif it is  undefinedor not. This is because  'Fetching Data'it is “true”, and then  &&always pass when it is listed first.

A new proposed feature: the optional concatenation

At the moment there is a proposal to allow “option chaining” when you try to return a property deep in a tree structure. Under the proposal, the question mark symbol  ?may be used to extract a property  only  if it is not  null.

For example, we could refactor our example above  this.state.data?.(), thus returning only  dataif it is not  null.

Or, if we were mainly concerned that  statewas defined or not, we could go back  this.state?.data.

The proposal is currently in Phase 1, as an experimental feature. You can read it  here  , and you can use it in your JavaScript now through Babel, adding  @ babel / plugin-proposal-optional-linking  to your  .babelrc files.

3. Convert to Boolean

CONVERSION OF TYPE

In addition to standard Boolean values  trueand  false, JavaScript also treats all other values as “truth” or “false”.

Unless otherwise defined, all values are in JavaScript ‘truthy’ with the exception of  0,  "",  null,  undefined,  NaNand, of course  false, that they are ‘falsy’.

We can easily switch from true to false negative using the operator  !, which also convert the type  "boolean".

IsTrue = const! 0; 
const IsFalse =! 1; 
alsoFalse !! const = 0; 
console.log (IsTrue); // Result: true 
console.log (typeof true); // Result: "boolean"

This kind of type conversion can be useful in conditional statements, even if the only reason you would choose to define  falseas  !1it is if you were playing golf code!

4. Convert to string

CONVERSION OF TYPE

To quickly convert a number to a string, we can use the concatenation operator  +followed by an empty set of quotation marks  "".

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

5. Convert to Number

CONVERSION OF TYPE

You can quickly get to the contrary by using the addition operator  +.

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

This can also be used to convert Boolean in numbers, as follows:

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

There may be contexts in which  +will be interpreted as the concatenation operator rather than the addition operator. When that happens (and you want to return an integer, not a floating) you can instead use two tilde:  ~~.

A tilde, known as “operator bitwise NOT”, is an equivalent operator  -n — 1. So, for example,  ~15it is equal to  -16.

The use of two consecutive tilde effectively cancels the operation because  â€” ( — n — 1) — 1 = n + 1 — 1 = n. In other words, it is  ~ — 16the same  15.

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

Although she can not think of many cases of use, the bitwise operator can also be used on boolean values:  ~true = -2and  ~false = -1.

6. rapid Powers

OPERATIONS

From ES7, it was possible to use the exponent operator  **as a shortcut to the powers, which is faster than writing  Math.pow(2, 3). This is a simple thing, but it makes the list because they have not been updated to include many tutorials this operator!

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

This should not be confused with the  ^symbol, commonly used to represent exponents, but in JavaScript is the bitwise XOR operator.

Before ES7, the shorthand existed only for powers with base 2, using the operator bitwise left shift  <<:

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

For example,  2 << 3 = 16it equals  2 ** 4 = 16.

7. Float quick on whole

TRANSACTIONS / TYPE OF CONVERSION

If you want to convert a float to an integer, you can use  Math.floor(),  Math.ceil()or  Math.round(). But there is also a faster way to truncate a float to an integer using  |the bitwise OR operator.

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

The behavior  |varies depending on whether you are dealing with positive or negative numbers, so it’s best to use this shortcut if you’re sure.

If  nit is positive,  n | 0round down. If  nit is negative, rounded up. To put it more accurately, this operation removes everything that follows the decimal point, a float on a truncating integer.

You can achieve the same effect by using rounding  ~~, as above, and in fact  any  bit bitwise would force a float to an integer. The reason that these particular operations work is that – when forced to a whole number – the value remains unchanged.

Remove final figures

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

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

Instead, the bitwise operator allows us to write:

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

8. Automatic Binding in classes

CLASSES

We can use the notation ES6 arrow in class methods and thus suggests a link. This often save several lines of code in our class constructor and we can happily say goodbye to repetitive expressions like!

this.myMethod=this.myMethod.bind(this)

React import, {} Component from React; 
Export default class App {extends Compononent 
   constructor (props) { 
      super (props); 
      this.state = {}; 
   } 

   MyMethod = () => { 
      // This method is implicitly bound! 
   } 

   Render () { 
    return ( 
      <> 
        <div> 
          {this.myMethod ()} 
        </ div> 
      </> 
    ) 
   } 

};

9. Truncate a matrix

ARRAYS

If you want to remove values from the end of an array in a destructive way, there are faster alternatives than using  splice().

For example, if you are familiar with the original size of the array, you can redefine 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 an especially concise solution. However, I found that the run-time  slice()method is even faster. If speed is your primary goal, consider using something like this:

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

10. Get the last elements in a matrix

ARRAYS

The array method  slice()can take negative integers and, if provided, will take values from the end of the array instead of the beginning.

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

11. Format the JSON code

JSON

Finally, you may have used  JSON.stringifybefore, but did you realize that it can also help you indent your JSON for you?

The  stringify()method takes two optional parameters: a  replacerfunction, which can be used to filter the JSON displayed, and a  spacevalue.

The  spacevalue takes an integer for the desired number of spaces or a string (for example,  '\t'to insert the cards) and can make reading the retrieved JSON data much simpler.

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

Overall, I hope you have found these tips useful as when I discovered them for the first time.

You have a few tricks JavaScript on your own? I’d love to read them in the comments below!


12. Length of the cache array [obsolete] in loop

LOOP

In the original version of this article, I shared a suggestion to store the length of the array in the cache  forloop. However, if it is a read-only cycle, modern JavaScript engines are dealing with this at compile time. It is no longer necessary unless the array length does not change (and, if so, you probably want to be recalculated with each iteration anyway).

Thanks to several developers who have stressed that. If you want to know more, take a look at  this question on StackOverflow  .

For those interested, there was a certain incentive to writing  for (let i = 0, len = array.length; i < len; i++)instead  for (let i = 0; i < array.length; i++). This is no longer the case!

Javascript fundamentals
Antonio Lamorgese

Network administrator and developer. After years of experience in the industry, I designed a MYSQL data management system in PHP without writing a single line of code. Find out more....