Shorthand JavaScript Techniques you should know in 2021

Thawinwats
4 min readJan 30, 2021

--

Short hand JavaScript Techniques you should know in 2021

If Presence

This is one of the common shorthand technique mostly used for
truth, null or undefined checks.

// Longhand
if (x === true) {
// do something
}

// Shorthand
if (x) {
// do something
}

If … else Ternary operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.

// Longhand
let test: boolean;
if (x > 10) {
test = true;
} else {
test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
// or we can use directly
let test = x > 10;

If with multiple conditions

By using includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

// Longhand
if (x === 'A' || x === 'B' || x === 'C' || x ==='D') {
// do something
}
// Shorthand
if (['A', 'B', 'C', 'D'].includes(x)) {
// do something
}

Or we can use the indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

// Longhand
if (x === 'A' || x === 'B' || x === 'C' || x ==='D') {
// do something
}
// Shorthand
if (['A', 'B', 'C', 'D'].indexOf(x) > -1) {
// do something
}
// Or
if (~['A', 'B', 'C', 'D'].indexOf(a)) {
// do something
}

Optional Chaining

The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to the . chaining operator

const data = { a: { b: { c: 10 } } }// Longhand
const result = data && data.a && data.a.b && data.a.b.c // 10
// Shorthand
const result = data?.a?.b?.c // 10

I have an article more about optional chaining in Thai language

Conditions in the key-value objects

We can store the many conditions in the objects and used it based on the conditions by key in object like the switch statement

// Longhand
switch (data) {
case 'A':
return func1();
case 'B':
return func2();
case 'C':
return func3();
default
return;
}
// Shorthand
const data = {
A: func1,
B: func2,
C: func3
};

data?.[some_key]?.();
// Example data.['B']?.() an output is call func2

Destructuring Assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

// Longhand
const x = data.x;
const y = data.y;
const z = data.z;
// Shorthand
const { x, y, z } = data;

Assigning values to multiple variables

// Longhand 
const x = 1;
const y = 2;
const z = 3;
// Shorthand
const [x, y, z] = [1, 2, 3];

Swap two variables

We can swap two variables with array destructuring assignment

let x = 'A', y = 'B'; // Longhand
const temp = x;
x = y;
y = temp;
// Shorthand
[x, y] = [y, x];
// output: x = 'B' and y = 'A'

Object Property Assignment

const name = "Chris"; 
const age = 25;
// Longhand
const obj = {
name: name,
age: age
};
// Shorthand
const obj = { name, age };
// output: {
name: "Chris",
age: 25
}

Arrow Function

An arrow function expression is a compact alternative to a traditional function expression

// Longhand 
function add(x, y) {
return x + y;
}
// Shorthand
const add = (x, y) => x + y;
add(1, 2) // output: 3

Default Parameter Values

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

// Longhand
const add = (x, y) => {
if (x === undefined) {
x = 1;
}
if (y === undefined) {
y = 2;
}
return x + y;
}
// Shorthand
const add = (x = 1, y = 2) => x + y;
add() // output: 3

Short Function Calling

Using an IIFE (Immediately Invoked Function Expression) techniques that runs as soon as function is defined.

// Longhand
const func1 = () => console.log('foo');
const func2 = () => console.log('bar');
const x = 1;if (x === 1) {
func1();
} else {
func2();
}
// Shorthand
(x === 1 ? func1 : func2)(); // output: foo

Template Literals

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

// Longhand
const welcome = "Hi "+ firstName + " " + lastName + "."
// Shorthand
const welcome = `Hi ${firstName} ${lastName}`;

Multi-line String

Any newline characters inserted in the source are part of the template literal.

// Longhand
const str = 'string text line 1\n'
+ 'string text line 2'
// Shorthand
const str = `string text line 1
string text line 2`

String into a Number

// Longhand 
const x = parseInt('123');
const y = parseFloat('12.3');
// Shorthand
const x = +'123';
const y = +'12.3';

Date into a Timestamp

const date = new Date() 
// output: Wed Jan 20 2021 10:10:40 GMT+0700 (Indochina Time)
// Longhand
const x = date.getTime() // output: 1611112240377
// Shorthand
const x = +date; // output: 1611112240377

Non-boolean value to a boolean value

It is possible to use a Double NOT (!!) operators in series to explicitly force the conversion of any value to the corresponding boolean primitive.

const expression = 'string or number'// Longhand 
const isTrue = Boolean(expression) // output: true
// Shorthand
const isTrue= !!expression; // output: true

--

--

Thawinwats
Thawinwats

No responses yet