16 JavaScript Protips [2020 Edition]

Written by johnson0x | Published 2020/03/20
Tech Story Tags: javascript | web-development | nodejs | angular | react | vuejs | programming | hackernoon-top-story

TLDR In this article, we’ll go over a list of tricks that will make you a better developer and supercharge your JavaScript skills. Each of these tricks accomplishes tasks that most developers need to do on a daily basis. The Set object type was introduced in ES6, and along with..., the ‘spread’ operator, we can use it to create a new array with only the unique values. The every and some functions are functions that not all developers are familiar with. They can be very useful in certain situations.via the TL;DR App

When I began learning JavaScript, I made a list of every time-saving trick that I found in other people’s code, on code challenge websites, and anywhere other than the tutorials I was using.
Each of these tricks accomplishes tasks that most developers need to do on a daily basis. Depending on your experience you might already know
some of these tricks, while others will blow your mind.
In this article, we’ll go over a list of tricks that will make you a better developer and supercharge your JavaScript skills.

1. Filter Unique Values

The Set object type was introduced in ES6, and along with ..., the ‘spread’ operator, we can use it to create a new array with only the 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, isolating unique values would involve a lot more code than that!
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’d need a different approach!)

2. Every and some

The every and some functions are functions that not all developers are familiar with. However, they can be very useful in certain situations. Let’s start with the every function. You can use this function if you want to know whether all elements of an array pass a certain test. Essentially what this is doing is going through each element of the array and checking to see if they’re all true.
This might sound a little abstract to you, so let’s lets take a look at the following example. It’s not as complex as it sounds.
const random_numbers = [ 13, 2, 37, 18, 5 ]
const more_random_numbers = [ 0, -1, 30, 22 ]

const isPositive = (number) => {
  return number > 0
}

random_numbers.every(isPositive); // returns true
more_random_numbers.every(isPositive); // returns false
The every function returns a boolean. If all elements in the array pass the test, true will be returned. If one of the elements in the array fails the test, false will be returned.
You could also use an anonymous function as a tester function if you’d like to:
random_numbers.every((number) => {
    return number > 0
})
The some function almost works exactly the same as the every function. There’s only one major difference: the some function tests whether at least one element in the array passes the test implemented.
If we take a look at the previous example and use the some function instead of the every function both arrays will return true, since both arrays contain a positive number.
const random_numbers = [ 13, 2, 37, 18, 5 ]
const more_random_numbers = [ 0, -1, 30, 22 ]

const isPositive = (number) => {
  return number > 0
}

random_numbers.some(isPositive); // returns true
more_random_numbers.some(isPositive); // returns true

3. Short-Circuit Evaluation

The ternary operator is a quick way to write simple (and sometimes not-so-simple) conditional statements, 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 the ‘and’
&&
and ‘or’ || logical operators to evaluate certain expressions in an even more concise way. This is often called ‘short-circuiting’ or ‘short-circuit evaluation’.

How It Works

Let’s say we want to return just one of two or more options.
Using
&&
will return the first
false
 
or ‘falsy’ value. If every operand evaluates to true , the last evaluated expression will be returned.
let one = 1, two = 2, three = 3;
console.log(one && two && three); // Result: 3

console.log(0 && null); // Result: 0
Using || will return the first
true
 
or ‘truthy’ value. If every operand evaluates to
false
 
, the last evaluated expression 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

Let’s say we want to return the
length
of a variable, but we don’t know the variable type.
We could use an
if/else
statement to check that
foo
is an acceptable type, but this could get pretty longwinded. Short circuit evaluation allows us to do this instead:
return (foo || []).length;
If the variable
foo
is truthy, it will be returned. Otherwise, the
length
 
of the empty array will be returned: 0 .

Example 2

Have you ever had problems accessing a nested object property? You
might not know if the object or one of the sub-properties exists, and
this can cause frustrating errors.
Let’s say we wanted to access a property called
data
within
this.state
, but
data
is undefined until our program has successfully returned a fetch request.
Depending on where we use it, calling
this.state.data
could prevent our app from running. To get around this, we could wrap it in a conditional:
if (this.state.data) {
  return this.state.data;
} else {
  return 'Fetching Data';
}
But that seems pretty repetitive. The ‘or’ operator provides a more concise solution:
return (this.state.data || 'Fetching Data');
We can’t refactor the code above to use
&&
. The statement
'Fetching Data'
&& this.state.data
will return
this.state.data
whether it is
undefined
or not. This is because
'Fetching Data'
is ‘truthy’, and so the
&&
will always pass over it when it is listed first.

A New Proposed Feature: Optional Chaining

There is currently a proposal to allow ‘optional chaining’ when
attempting to return a property deep in a tree-like structure. Under the
proposal, the question mark symbol
?
could be used to extract a property only if it is not
null
.
For example, we could refactor our example above to
this.state.data?.()
, thus only returning
data
if it is not
null 
.
Or, if we were mainly concerned about whether
state
was defined or not, we could return
this.state?.data
.

4. Convert to Boolean

Besides the regular boolean values
true
and
false
, JavaScript also treats all other values as either ‘truthy’ or ‘falsy’.
Unless otherwise defined, all values in JavaScript are ‘truthy’ with the exception of
0
,
""
,
null
,
undefined
,
NaN
and of course
false
, which are ‘falsy’.
We can easily switch between true and false by using the negative operator ! , which will also convert the type to
"boolean"
.
const isTrue  = !0;
const isFalse = !1;
const alsoFalse = !!0;

console.log(isTrue); // Result: true
console.log(typeof true); // Result: "boolean"
This kind of type conversion can be handy in conditional statements, although the only reason you’d choose to define
false
as
!1
is if you were playing code golf!

5. Conditionally setting a variable

Conditionally setting a variable is both easy and makes your code look more elegant. There’s no need to write an if-statement when applying this trick — which personally is one of my favorite tricks in JavaScript.
So how can you conditionally set a variable?
const timezone = user.preferred_timezone || 'America/New_York'
In the example above we check if the user has a preferred timezone. If the user has a preferred timezone, we use that timezone. If the user doesn’t have a preferred timezone we use the default timezone, which is
‘America/New_York’
.
This code looks so much cleaner than when using an if-statement.
let timezone = 'America/New_York'

if (user.preferred_timezone) {
    timezone = user.preferred_timezone
}
Looks much cleaner, doesn’t it?

6. Convert to String

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"

7. Convert to Number

The opposite can be quickly achieved using the addition operator
+ 
.
let int = "15";
int = +int;

console.log(int); // Result: 15
console.log(typeof int); Result: "number"
This may also be used to convert booleans to numbers, as below:
console.log(+true);  // Return: 1
console.log(+false); // Return: 0
There may be contexts where the
+
will be interpreted as the concatenation operator rather than the addition operator. When that happens (and you want to return an integer, not a float) you can instead use two tildes:
~~
.
A tilde, known as the ‘bitwise NOT operator’, is an operator equivalent to
 -n — 1 
. So, for example,
~15
is equal to
-16
.
Using two tildes in a row effectively negates the operation, because
 — ( — n — 1) — 1 = n + 1 — 1 = n 
. In other words,
~ — 16
equals
15
.
const int = ~~"15"

console.log(int); // Result: 15
console.log(typeof int); Result: "number"
Though I can’t think of many use-cases, the bitwise NOT operator can also be used on booleans:
~true = -2
and
~false = -1
.

8. Casting values in Arrays

Sometimes you want to cast all values in an array. One of those
occurrences could be when you’re using the triple equals operator to
check whether a certain number exists in an array, for example.
I lately ran into a problem where I had a multi-select. The HTML
values of the select options were strings instead of integers, which
makes sense. The array of selected values looked like this:
let selected_values = [ '1', '5', '8' ]
The problem was that I was checking if a certain integer existed in the
array of the selected values. Without success. I used an intersect
function that used the triple equals operator. And since ‘5’ !== 5 I had to find a solution.
The prettiest solution, in my opinion, was to cast all values in the
array to an integer. When trying to do this I stumbled upon a painfully
simple, yet elegant, solution.
selected_values = selected_values.map(Number) // [ 1, 5, 8 ]
Instead of casting all values to an integer, you could also cast all values in
the array to a boolean by simply changing the argument of the map
function.
selected_values = selected_values.map(Boolean)

9. Quick Powers

Since ES7, it has been possible to use the exponentiation operator
**
as a shorthand for powers, which is faster than writing
Math.pow(2, 3)
. This is straightforward stuff, but it makes the list because not many tutorials have been updated to include this operator!
console.log(2 ** 3); // Result: 8
This shouldn’t be confused with the ^ symbol, commonly used to represent exponents, but which in JavaScript is the bitwise XOR operator.
Before ES7, shorthand existed only for powers 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
.

10. Quick Float to Integer

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 behaviour of
|
varies depending on whether you’re dealing with positive or negative numbers, so it’s best only to use this shortcut if you’re sure.
If
n
is positive,
n | 0
effectively rounds down. If
n
is negative, it effectively rounds up. To put it more accurately, this operation removes whatever comes after the decimal point, truncating a float to an integer.
You can get the same rounding effect by using
~~
, as above, and in fact any bitwise operator would force a float to an integer. The reasons these
particular operations work is that — once forced to an integer — the
value is left unchanged.

Remove Final Digits

The bitwise OR operator can also be used to remove any amount of
digits from the end of an integer. This means we don’t have to use code
like this to convert between types:
let str = "1553"; 
Number(str.substring(0, str.length - 1));
Instead, the bitwise OR 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

11. Object destructuring

Once you know about object destructuring it’s probably something that you’re going to be using every single day.
But what exactly is destructuring?
Destructuring is a JavaScript expression that allows you to extract
data from arrays, objects, maps and sets into their own variable. It
allows you to extract properties from an object or items from an array,
multiple at a time.
Let’s take a look at the following example where we have a user
object. If you want to store the user’s name in a variable you have to
assign it to a variable on a new line. And if you want to store the
gender as well in a variable, you’d have to do the same again.
const user = {
    name: 'Frank',
    age: 23,
    gender: 'M',
    member: false
}

const name = user.name
const gender = user.gender
With destructuring you can directly get the variables for the object’s properties using the following syntax:
const { name, age, gender, member } = user;

console.log(name)   // Frank
console.log(age)    // 23
console.log(gender) // M
console.log(member) // false

12. Automatic Binding in Classes

We can use ES6 arrow notation in class methods, and by doing so
binding is implied. This will often save several lines of code in our
class constructor, and we can happily say goodbye to repetitive
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>
      </>
    )
  }
};

13. Better debugging using performance

One of the things that you’ll do a lot as a developer is debugging.
However, debugging is more than just printing out a bunch of log
messages in your console using console.log.
Did you know that the console object has a great way to analyze
performance of pieces of your code? However, most developers only know
about the standard console.log way of debugging their code.
The console object has way more helpful functions. It has a time and timeEnd function that can help you analyzing performance. It works really simple.
In front of the code that you want to test, you call the console.time
function. This function has one argument, which takes a string that
describes what you want to analyze. At the end of the code that you want
to test, you call the console.timeEnd function. You give this
function the same string as the first parameter. You’ll then see the
time it took to run the code in your console.
console.time('loop')  

for (let i = 0; i < 10000; i++) {   
    // Do stuff here 
}  console.timeEnd('loop')

14. Truncate an Array

Arrays
If you want to remove values from the end of an array destructively, there’s are faster alternatives than using
splice()
.
For example, if you know the size of your original array, you can re-define its length property, like so:
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:
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]

15. Get the Last Item(s) in an Array

Arrays
The array method
slice()
can take negative integers, and if provided it will take values from the end of the array rather than 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]

16. Format JSON Code

JSON
Lastly, you may have used JSON.stringify before, but did you realise it can also help indent your JSON for you?
The stringify() method takes two optional parameters: a replacer function, which you can use to filter the JSON that is displayed, and a space value.
The space value takes an integer for the number of spaces you want or a string (such as '\t' to insert tabs), and it can make it a lot easier to read fetched JSON data.
console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));

// Result:
// '{
//     "alpha": A,
//     "beta": B
// }'
Overall, I hope you found these tips as useful as I did when I first discovered them.
Got any JavaScript tricks of your own? I’d love to read them in the comments below!

Published by HackerNoon on 2020/03/20