Javascript

Modern JavaScript Shorthands

Short hand alternatives can help reduce many lines of code and save plenty of time. In this article I will be discussing...

Written by Luci · 2 min read >

Short hand alternatives can help reduce many lines of code and save plenty of time. In this article I will be discussing about a few commonly used short hands.

1. Short circuit evaluation

  • The following shorthand uses the logical OR ( || ) to assign a default value to a variable. If the left hand side of the ( || ) has a non falsy value it will be assigned to the variable if not the default value (right hand side of the operator) will be assigned.

Longhand

let baseUrl; 

// Conditionally assign value if baseurl exists from env file.
if (process.env.baseurl) {
  baseUrl = process.env.baseurl;
} 
else {
  baseUrl = "www.google.com";
}

Shorthand

const baseUrl = process.env.baseUrl || "www.google.com"
  • Keep in mind that 0 is considered as a falsy value in this operator. If 0 is a value that is intended to be there use the Nullish coalescing operator instead. (??)

2. Convert a string to an integer.

  • The unary operator or commonly known as (+) can be used to convert a a string that is a number to integer format.

Longhand

const numberInString = "10";
const number = parseInt(numberInString);

Shorthand

// We can convert any number in string format to a number using the + operator
const numberInString = "10";
const number = +numberInString;
  • Keep in mind that non integer strings such as “abc” or “1.21” will output NaN as it only expects integers.

3. Ternary Operator

  • The ternary operator or the conditional operator is a simple and cleaner approach instead of if … else statements.

Longhand

const marks = 80;
let grade;
if (marks >= 50) {
  grade = 'pass';
} else {
  grade = 'fail';
}

Shorthand

const marks = 80;
const grade = marks>=50 ? "pass" : "fail";

4. (?.) Optional chaining (Typescript)

  • With the use of ? along with dot notation we can access object values. When a key or value does not exist in dot notation it will throw an error but if optional chaining is used it will return undefined and continue the execution of the program.

Longhand

const student = {
    Gerald: {
        marks: 50,
    },
};

// Print the marks of the student. 

// If we dont check this and if student is undefined it will throw an error
if (student && student.Gerald&& student.Gerald.marks ) {
  console.log(student.Gerald.marks)
}

Shorthand

const student = {
    Gerald: {
        marks: 50,
    },
};

// Print the marks of the student.

console.log(student?.Gerald?.marks) // Will not throw an error if value is empty

5. Spread operator

  • The spread operator can be used to access values from arrays and objects. Common array functions such as concat can be easily replaced using the spread operator.
  • Combine two arrays

Longhand

const array1 = [1,2];
let array2;

array2 = array1.concat([3,4,5]);

Shorthand

const array1 = [1,2];
let array2;

array2 = [...array1, 3,4,5];

6. Rest Parameters (…)

  • The rest parameter can be used to accept an unknown number of arguments.

Longhand

const add2Numbers = (num1,num2) => { 
  return num1+num2;
}

const add3Numbers = (num1,num2,num3) => { 
  return num1+num2+num3;
}

add2Numbers(1,2);
add3Numbers(1,2,3);

Shorthand

const addAll = (...numbers) => { 
  let total = 0;
  for (let num of numbers) total += num;
  return total;
}

addAll(1,2);
addAll(1,10,50);
addAll(20,20,1231,111);

// All of the above syntaxes will work and functions will not have to be defined again

7. Destructuring

  • As the name implies destructuring can be used to extract the specific items that are only required. Variables can be assigned values easily from arrays and objects using this concept.
  • Get values from objects

Longhand

const student = {name: "Purple", skill: "UI/UX"};

const name = student.name;
const skill = student.skill;

console.log(name); // Purple
console.log(skill); // UI/UX

Shorthand

const student = {name: "Purple", skill: "UI/UX"};

// Required values can be taken out from the object as seperate variables
const {name, skill} = student;

console.log(name); // Purple

// Refactor to an alias of your choice

const {name: firstName} = student;

console.log(firstName); // Purple

// Set default value if it doesnt exist.

const {name, age=24 } = student;

console.log(age); // 24
  • Get values from arrays

Longhand

const phase = ["Kratos","Oops","Saber","Garfield","Mojo"];

const value1 = phase[0]; // Kratos
const value2 = phase[1]; // Oops

Shorthand

const phase = ["Kratos","Oops","Saber","Garfield","Mojo"];

//desctructure values from array

const [value1,value2, ...others] = phase;

console.log(value1) // Kratos
console.log(value2) // Oops
console.log(others) // ["Saber","Garfield","Mojo"]

Further reading :-

  1. Short circuit evaluation
  2. Optional chaining
  3. Ternary Operator
  4. Spread operator
  5. Rest parameters
  6. Destructing
  7. The modern JavaScript tutorial
Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x