11 JavaScript tips you won’t find in most tutorials
- Tram Ho
Since I started learning JavaScript, I’ve made a list of time-saving tips that I find in other people’s code, on website challenge codes, and anywhere other than the tutorials I’m using. .
I have built this list since then, and in this article, I will share 11 tips I have chosen for myself that I think is particularly useful. This article will be useful for beginners, but I also hope that even programmers who have experienced for a while will find something new in this list.
The list will be divided into several categories: some tips are easy to use in all cases, some may be more suitable for short-term code challenges / codes than for production code, where it is necessary to be more transparent. brief analysis – you will be the one to classify it!
In no particular order, here are 11 neat ways to write shorter and more efficient code.
1. Filter Unique Values
ARRAYS
Set
type object has been introduced in ES6, along with …
, ‘spread’ operator, we can use it to create a new array of unique values (unique values).
1 2 3 | const array = [1, 1, 2, 3, 5, 5, 1] const uniqueArray = [...new Set(array)]; console.log(uniqueArray); // Result: [1, 2, 3, 5] |
Before ES6, independent unique values would require a lot more code!
This tip applies to arrays containing primitive types: undefined
, null
, boolean
, string
and number
. (If you have an array containing additional objects, functions, or arrays, you’ll need a different approach.)
2. Short-Circuit Evaluation
CONDITIONALS
The Ternary operator is a quick way to write simple conditional statements (and can sometimes not be very simple), for example:
1 2 | 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 referred to as a ‘short-circuiting’ or ‘short-circuit evaluation’.
The way it works
Suppose we want to return only 1 of 2 or more options.
Using &&
will return false
or the first “falsy” value. If each operand evaluates to true
, the last evaluated expression will be returned.
1 2 3 4 | let one = 1, two = 2, three = 3; console.log(one && two && three); // Result: 3 console.log(0 && null); // Result: 0 |
Use ||
will return true
or the first “truthy” value. If each operand evaluates to false, the final evaluated expression will be returned.
1 2 3 4 | 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 the length
of a variable, but we don’t know the variable type.
We can use an if/else
to check if the type of foo
is accepted, but this can be a bit verbose. Instead, the short circuit evaluation allows us to do this:
1 | return (foo || []).length; |
If the variable of foo
is truthy, it will be returned. Otherwise, the length
of the empty array will be returned: 0
.
Example 2:
Have you ever had trouble accessing 1 nested object property? You won’t know if an object or one of the sub-properties exists, and this can cause nasty errors.
Suppose we want to access a property named data
inside this.state
, but the data
is not defined until our program successfully returns a fetch request.
Depending on where we use it, calling this.state.data
may prevent our app from running. To solve this problem, we can grab it into a conditional command:
1 2 3 4 5 | if (this.state.data) { return this.state.data; } else { return 'Fetching Data'; } |
But that also seems a bit repetitive. The ‘or’ operator can resolve it more quickly:
1 | return (this.state.data || 'Fetching Data'); |
We cannot refactor the code above to equal &&
. Statement 'Fetching Data' && this.state.data
will return this.state.data
whether it is undefined or not. This happens because 'Fetching Data'
is ‘truthy’, so &&
will always pass it when it is first listed.
1 new proposed feature: Optional chain – Optional Chaining
There is currently a proposal to enable ‘optional chaining’ when trying to return a property within a ‘tree-like’ structure. As suggested, the question mark icon ?
can be used to output a property only if it is not null
.
For example, we can refactor the above example to this.state.data?.()
, So return data
when it is not null
.
Or, if we only care about whether the state
is defined or not, we can return this.state?.data
.
The request command is in Stage 1, as an experimental feature. You can read about it here , and you can use it right in your JavaScript thanks to Babel, by adding @ babel / plugin-proposal-optional-chaining to your .babelrc
file.
3. Convert into Boolean
TYPE CONVERSION
Besides the usual boolean values true
and false
in, JavaScript also treats all other values like ‘truthy’ or ‘falsy’.
Unless they have been specified, all values in JavaScript are ‘truthy’ with the exception of 0
, “”
, null
, undefined
, NaN
and of course false
, which is “falsy”.
We can easily switch between true and false using the negative operator !
, which will also convert the type to “boolean"
.
1 2 3 4 5 6 | const isTrue = !0; const isFalse = !1; const alsoFalse = !!0; console.log(isTrue); // Result: true console.log(typeof true); // Result: "boolean" |
This type conversion can be quite handy when dealing with conditional statements, even though the only reason you’ll choose to determine !1
is false
if only when you’re playing the code!
4. Convert to String
TYPE CONVERSION
To quickly convert a number into a string, we can use the concatenation operator +
followed by an empty set of quotation marks “”
.
1 2 3 4 | const val = 1 + ""; console.log(val); // Result: "1" console.log(typeof val); // Result: "string" |
5. Convert to Number
TYPE CONVERSION
The opposite can be quickly obtained by addition operator +
.
1 2 3 4 5 | let int = "15"; int = +int; console.log(int); // Result: 15 console.log(typeof int); Result: "number" |
This can also be used to convert booleans into numbers, as shown below:
1 2 | console.log(+true); // Return: 1 console.log(+false); // Return: 0 |
The +
case will operate as a concatenation operator rather than the addition operator, which may occur. Then (and you want to return 1 integer, not 1 real number) you can use 2 tildes: ~~
instead.
A tilde, known as ‘bitwise NOT operator’, is an operator equivalent to -n - 1
. So, for example, ~15
would be equal to -16
.
Using 2 consecutive tildes effectively regulates the operation, because - ( - n - 1) - 1 = n +1 - 1 = n
. In other words, ~-16
equals 15
.
1 2 3 4 | const int = ~~"15" console.log(int); // Result: 15 console.log(typeof int); Result: "number" |
Although I don’t think in most use cases, this bitwise can also be used on booleans: ~true = -2
and ~false = -1
.
6. Quick Powers
OPERATIONS
From ES7, it was possible to use exponential operators **
as shorthand for power, which is faster than writing Math.pow(2, 3)
. This is a simple tool, but it is still on the list because not many new updated tutorials include this operator!
1 | console.log(2 ** 3); // Result: 8 |
This should not be confused with the ^
sign, which is commonly used to represent exponents, but in JavaScript it is a ‘bitwise XOR operator’.
Before ES7, shorthand only existed for power with base 2, using the bitwise left shift operator <<
:
1 2 3 4 5 | // The following expressions are equivalent: Math.pow(2, n); 2 << (n - 1); 2**n; |
For example, 2 <<3 = 16
is the same as 2 **4 = 16
.
7. Quick Float to Integer – Quickly convert real numbers to whole numbers
OPERATIONS / TYPE CONVERSION
If you want to convert a real number into an integer, you can use Math.floor()
, Math.ceil()
or Math.round()
. But there is also a faster way to convert a real number into an integer equal to |
, it is a ‘bitwise OR operator’.
1 2 | console.log(23.9 | 0); // Result: 23 console.log(-23.9 | 0); // Result: -23 |
Behavior of |
quite diverse based on whether you are working with positive or negative numbers, so only use this shortcut when you are sure.
If n
is positive, n | 0
rounded down effectively. If n
is negative, it will round up effectively. To increase its accuracy, this operation removes anything that comes after the decimal point, cutting the actual number into an integer.
You can get the rounding effect by using ~~
, as above, and the fact that any bitwise operator will force a real number to be an integer. The reason these special operations work is because – 1 when bound to an integer – the value is kept intact.
Remove the last digits – Remove Final Digits
‘Bitwise OR operator’ can also be used to delete the last number of an integer. This means we don’t need to use code like this to switch between types:
1 2 | let str = "1553"; Number(str.substring(0, str.length - 1)); |
Instead, the bitwise OR operator allows us to write:
1 2 3 | 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 arrow symbol ES6 in the class method, which will use binding. It will usually save a few lines of code in the class constructor, and we can say hello to repeated expressions like .myMethod = this.myMethod.bind(this)
!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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> </> ) } }; |
9. Truncate 1 Array
ARRAYS
If you want to remove the values from the end of an array thoroughly, there are many quicker alternatives than using slice()
.
For example, if you know the size of the initial array, you can redefine its property length, such as:
1 2 3 4 | 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 special concise solution. However, I have found that the run-time of the slice()
method is even faster. If speed is your main goal, consider using these:
1 2 3 4 | 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] |
10. Get 1 (or more) Items in 1 Array
ARRAY
The array slice()
method can take negative integers, and if provided it will take values from the end of the array instead of the beginning.
1 2 3 4 5 | 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 JSON code
JSON
Finally, you may have used JSON.stringify
before, but did you realize that it can also help indent – JSON indent for you?
The stringify()
method takes two optional parameters: a function replacer
, which you can use to filter the displayed JSON, and a space
value.
This space
value takes an integer that represents the number of spaces – the space you want or a string (such as 't'
to insert tabs), and makes it much easier to read the JSON data fetched.
1 2 3 4 5 6 7 | console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, 't')); // Result: // '{ // "alpha": A, // "beta": B // }' |
Epilogue
Hope you find these tips useful and find the right way to apply them to your project.
If you have any tips of your own, don’t forget to share them!
Tech Talk via Medium
Source : Techtalk