These practices are what makes our code cleaner, readable, more comprehensible and simpler.
Sometimes, the code you write is perfectly valid, usable and somewhat readable, but you might be going the long way around addressing problem. Maybe that’s because you haven’t made an effort to start using newer syntax, or that you’re stuck in how you work and your thought processes.
It might be time to change your habits by creating new ones; replacing them with shorthand alternatives for solving the same problem. It will involve asking yourself questions constantly until you are used to the new approach.
The shorthand expressions that will be discussed have their limitations. They are not always the right option, as with any tool. However, they are valid language features & syntax.
You may have strong feelings towards some of the code used. If so I would like to hear them!
Let’s start with a simple one…
Use ‘truthy’ to its full potential
Instead of using a complex if
condition to check whether a value is truthy, you can just simply use the variable itself as the condition. You need to know the logic behind a truthy value however.
false
, 0
, 0n
, ""
, null
, undefined
, and NaN
.Before
if (condition !== undefined && condition !== null) {
// handle truthy condition
}
After
if (condition) {
// handle truthy condition
}
Stop using so many if-else statements
Ternary Operators are frequently used as a shortcut to an if statement. It is simply asking a question (the condition), with which you execute some code if the answer is yes (truthy) or no (falsy).
Therefore, there are three parts to the statement: the condition to evaluate, the truthy expression, and the falsy expression.
condition ? exprIfTrue : exprIfFalse
Before
if (num > 5) {
return 'number is above 5';
} else {
return 'number is not above 5';
}
After
return num > 5 ? 'number is above 5' : 'number is not above 5';
When ternary operators get messy
Ternary operators are recommended for a single expression. You can use them to execute code based on the condition: condition ? executeThis() : executeOther()
or assign to variables const num = condition ? 3 : 5;
.
It gets messy when you introduce multiple ternary operators together into a single expression. For example…
((typeof val === 'string' ? runStringFunction() : false) ? runFunctionWhenStringFuncTrue() ? 'ok' : 'might be ok') : 'exited early so not ok'
The logic might not be clear at first glance, but you want it to be! For your future self and your peers.
When intent starts to become unclear, you should break them up into single statements or use an if-else statement.
if (typeof val === 'string') {
if (runStringFunction()) {
if (runFunctionWhenStringFuncTrue()) {
return 'ok';
}
return 'might be ok';
}
}
return 'exited early so not ok';
Bonus (omit the ‘else’)
As you can see from above if-else, you can omit the else if you return
within the if
statement. The return
would cause the function to return early, making the else
redundant (therefore you don’t need it for the logic to work as intended).
(Do you really need an if-else for variable assignment)
Short-Circuit Evaluation is a condition where the logical operator used, in addition to the precedence, dictates whether the statement should take the return value early (short circuit). It allows you to prevent unnecessary execution of code.
(some falsy expression) && _expr_
is short-circuit evaluated to the falsy expression;(some truthy expression) || _expr_
is short-circuit evaluated to the truthy expression.Before
let value; // we want to assign 'other' to 'value' if it is not null or undefined
if (other !== undefined && other !== null) {
value = other;
return value;
}
value = 'other was falsy';
return value;
After
const other = '';
value = other || 'other was falsy'; // will return 'other was falsy'
Bonus: Non-Boolean values
Short circuit evaluation, when used with non-boolean values, can return non boolean values.
const other = '';
const value = other || 'other falsy'; // returns 'other falsy'
other = 'Im truthy now';
value = other && ''; // returns 'Im falsy now'
However be careful with introducing complexity. You begin to sacrifice the benefits of short circuit evaluation when you introduce multiple logical operators. It’s a breeding ground for irritatingly simple (but easy to miss) bugs.
This is due to operator precedence. It is important to note that the &&
will be evaluated first due to precedence, unless you wrap the separate logical operator conditions in parenthesis.
true || false && false // returns true, because '&&' is executed first
(true || false) && false // returns false, due to no precedence
An arrow function expression is a syntactically compact alternative to a regular function. It does not have it’s own bindings to this
, arguments
, super
or new.target
.
Using an arrow function makes our code more concise, simplifies scoping and this
.
Before
const func = function() {
// do something
}
After
const func = () => { return 'something'; }
func();
// OR
const func = () => 'something';
// OR WITH PARAM (SINGLE)
func();
const func = arg => {
console.log(arg);
}
func('hello');
// OR WITH MULTI PARAMS
const func = (arg, arg1) => {
console.log('arg: ', arg);
console.log('arg1: ', arg1);
};
func('hello', 'there');
Use the forEach
Array Prototype method
It allows you to iterate over elements an operate on them one at a time. The operation on each element is provided through the callback parameter. It looks cleaner and is easier to infer intent.
Before
const array = ['1', '2', '3'];
for (const val of array) {
}
// or
for (let i = 0; i < array.length; i++) {
}
After
const array = ['1', '2', '3'];
array.forEach(val => {
// do something
})
However, one drawback is that you cannot terminate a **forEach**
execution early, as you can with regular for..of
statements. If you require the possibility for early termination, then this isn’t the correct tool.
There may be a difference in performance of the
forEach()
compared to other for loops. Tests have shown that[forEach](https://github.com/dg92/Performance-Analysis-JS)
is significantly slower, however for simple tasks there should be no real performance concern.
The spread operator allows an iterable to be expanded where there are zero or more arguments, such as elements in an array or key-value pairs for objects.
Before
const array1 = [0, 1, 2, 3, 4];
const array2 = [5, 6, 7, 8, 9];
function(array1, array2) {
for (const value of array2) {
array1.push(value);
}
}
After
const array = [0, 1, 2, 3, 4];
const other = [5, 6, 7, 8, 9];
function(array1, array2) {
return [ ...array1, ...array2 ];
}
The rest operator allows an indefinite number of arguments, represented as an array.
Before
function add(x, y, z?) {
return x + y + (z || 0);
}
add(1, 2, 3)
After
function add(...nums) {
return sum(...nums);
}
add(1, 2, 3, 4, 5);
add(1, 3);
add(4, 5, 3, 4);
When assigning values to objects, sometimes you want to check whether they are truthy (have been defined and are not null etc).
If they are falsy you might want to fallback to default values. You can achieve this with the spread operator. The second spread has the ability to overwrite object values that have already been defined, otherwise the defaultValues
are kept.
Therefore, the default values are used as the first spread so that the second spread overwrites the first.
Before
function handleParams(params?: any) {
const finalParams = {
one: params && params.one ? params.one,
two: params && params.two? params.two,
three: params && params.three ? params.three
};
// do something with the params
}
After
const defaultValues = {
one: 'oneDefault',
two: 'twoDefault'
three: 'threeDefault'
};
function handleParams(params?: any) {
const finalParams = { ...defaultValues, ...params };
// do something with the params
return finalParams;
}
handleParams({one: 'oneNew', three: 'threeNew'});
// will return {one: 'oneNew', two: 'twoDefault', three: 'threeNew'}
This is just a simple replacement for a for loop iterating over each index of an iterable. Using a while
loop with a decrementing value val--
will count down to zero (which itself is falsy) to end the loop.
It looks cleaner (to me) and easy to understand what you are iterating over at first glance.
Before
for (let i; i < array.length; i++) {
// do something
}
After
const length = array.length;
while(length--) {
// do something
}
Checking if a value is in an Array
The bitwise NOT operator can be used with an indexOf
statement to check whether a value exists in an Array
or String
.
Where we would normally check whether the return value from the indexOf
operation was more than -1
, the tilde ~
will return true if indexOf
returns 0 or higher.
The logic behind the bitwise NOT is
~n == -(n+1)
.
Before
const array = [0, 1, 2, 3, 4];
if (array.indexOf(5) > -1) {
return 'exists';
} else {
return 'does not exist';
}
After
const array = [0, 1, 2, 3, 4];
if (~array.indexOf(4)) // true
This simpler syntax can also be achieved with Array.prototype.find
and Array.prototype.includes
.
if (array.includes(3)) // true
if (array.find(val => val === 2)) // true
We would use an IIFE
(Immediately-Invoked Function Expression) when there is code which we want to be executed immediately on parsing by the browser, and/or if we do not want to pollute the namespace with conflicting variables. It essentially introduces another scope.
It is useful if you need to execute a function immediately after declaring it. It combines the declaration + execution in one concise expression.
Before
function random() {
// do something
}
random()
After
!function() {
}()
(function() {})()
You can use any unary operator in place of !
to self-execute a function.
~function(){}()
+function(){}()
You may also like: Keeping your JavaScript code clean forever and scalable.
These shorthand expressions are intended to make code simpler and cleaner.
Therefore, it is counter-productive and defeats the original purpose to use multiple shorthand expressions together.
Thank you for reading!
#javascript #cleanercode #JavaScript code #tutorial