JavaScript code optimization by examples

In this article we will learn some optimization techniques which enables you to write a readable and optimized code with examples.

IF With Multiple conditions

//longhand
let num=1;
if(num===1||num===2||num===3||num===4){
	console.log("Num is less than five")
}
//shorthand
let num = 1;
const numsLessThanFive = [1,2,3,4];
if(numsLessThanFive.includes(num)){
	console.log("Num is less than five")
}
//or
numsLessThanFive.includes(num)&&console.log("Num is less than five")

If Else Shorthand

//longhand
let check;
let num = 10;
if(num>10){
	check=false;
}else{
	check=true;
}
console.log(check);
//shorthand
let num = 10;
let check = num>10?false:true;
console.log(check)

And if we have nested conditions

let num = 10;
let check = num>10?"GT 10":num<10?"LT 10":"ET 10";
console.log(check);

Defining variables

When you want to define multi variables which have the same type or same value.

//variables has same value
//longhand
let firstNum;
let secondNum;
let thirdNum;
firstNum=1;
secondNum=1;
thirdNum=1
//shorthand
let firstNum,secondNum,thirdNum;
firstNum=secondNum=thirdNum=1;

//variables have different values
let [firstNum,secondNum,thirdNum]=[10,20,30]

Null , Undefined and empty check also assigning default value

//longhand
let data="new test info";
let check;
if(data !=="" || data !== null || data !== undefined){
	check=data;
}else{
	check="No data";
}
console.log(check);
//shorthand
let data = "new test info";
let check = data||"No data";
console.log(check);

Assigning operator shorthand

//longhand
let firstNum,secondNum,thirdNum;
firstNum=secondNum=thirdNum=1;
firstNum = firstNum+1;
secondNum = secondNum-1;
thirdNum = thirdNum * 10;
console.log(firstNum,secondNum,thirdNum);
//shorthand
let firstNum,secondNum,thirdNum;
firstNum=secondNum=thirdNum=1;
firstNum++;
secondNum--;
thirdNum*=10;
console.log(firstNum,secondNum,thirdNum)

If presence shorthand

//longhand
let check=true;
if(check===true){
	//do something here
}
//shorthand 
if(check){
	//do something here
}

And if we have opposite conditions

//longhand
let check=true;
if(check!==true){
	//do something here
}
//shorthand
if(!check){
	//do something here
}

And operator && for multiple condition

//longhand
let userRole="admin";
const allowDeletePosts=()=>{
	console.log("all posts deleted from db by admin")
}
if(userRole==="admin"){
	allowDeletePosts();
}
//shorthand
let userRole="admin";
const allowDeletePosts=()=>{
	console.log("all posts deleted from db by admin")
}
userRole==="admin"&&allowDeletePosts();

For Loop Shorthand

const users = ["ahmed", "ali", "mohamed", "diaa"];
//longhand
for (let start = 0; start < users.length; start++) {
  console.log(users[start]);
}
//shorthand
for (let user of users) {
  console.log(user);
}
users.forEach((user) => {
  console.log(user);
});

Comparison returns

let check = "Data checked successfully";
const checkData = () => {
  return "Data under processing";
};
//longhand
const dataStatus = () => {
  if (check) {
    return "Data checked successfully";
  } else {
    return checkData();
  }
};
console.log(dataStatus());
//shorthand
const dataStatus = () => {
  return check || checkData();
};
console.log(dataStatus());

Arrow function

//longhand
function addNum(...nums) {
  return nums.reduce((prev, curr) => {
    return prev + curr;
  });
}
console.log(addNum(10, 20, 30, 40));
//shorthand
const addNum = (...nums) => {
  return nums.reduce((prev, curr) => {
    return prev + curr;
  });
};
console.log(addNum(10, 20, 30, 40));

Short function calling

//longhand
let operationType = "update";
const updateUser = () => {
  console.log("User has been updated");
};
const deleteUser = () => {
  console.log("User has been deleted");
};
if (operationType === "update") {
  updateUser();
} else {
  deleteUser();
}
//shorthand
(operationType === "update" ? updateUser : deleteUser)();

Default parameters

//longhand
function sum(firstNum, secondNum) {
  if (!firstNum) {
    firstNum = 1;
  }
  if (!secondNum) {
    secondNum = 1;
  }
  return firstNum + secondNum;
}
console.log(sum());
//shorthand
const sumNum = (firstNum = 1, secondNum = 1) => {
  return firstNum + secondNum;
};
console.log(sumNum(7, 3));

Spread operator

We can use spread operator for joining arrays.

//longhand
const admins = ["Ahmed", "Mohamed", "Diaa"];
const members = ["Islam", "Ali"];
const users = admins.concat(members);
console.log(users);
//shorthand
const allAdmins = ["Ahmed", "Mohamed", "Diaa"];
const allMembers = ["Islam", "Ali"];
const allUsers = [...allAdmins, ...allMembers];
console.log(allUsers);

Also for cloning arrays we can use spread operator

//longhand
const activeUsers = ["Ahmed", "Mohamed", "Ali"];
const users = activeUsers.slice();
console.log(users);
//shorthand
const activeAccounts = ["Ahmed", "Mohamed", "Ali"];
const allUsers = [...activeAccounts];
console.log(allUsers);

Template literals

If you are using + for concatenate multiple variables template literals simplify this.

//longhand
let firstName = "Ahmed";
let secondName = "Mahmoud";
console.log("Your name: " + firstName + " " + secondName);
//shorthand
let fName = "Ahmed";
let lName = "Mahmoud";
console.log(`Your name: ${fName} ${lName}`);

We can use it also when dealing with multi line of strings

//longhand
let msg =
  "Hello my name is ahmed and programming is" +
  "the most thing  i like web development using php,nodejs,javascript";
//shorthand
let newMsg = `Hello my name is ahmed and 
programming is the most thing  i like web development using php,nodejs,javascript`;

Object property assignment

when key and value have the same name we can define it directly in the object without adding value variable.

//longhand
let name = "Ahmed";
let age = 29;
let user = { name: name, age: age };
console.log(user);
//shorthand
let enhancedObj = { name, age };
console.log(enhancedObj);

converting string into numbers

//longhand
let firstNum = "102";
let secondNum = "19.5";
let firstConvertedNum = parseInt(firstNum);
let secondConvertedNum = parseFloat(secondNum);
console.log(
  typeof firstNum,
  typeof secondNum,
  typeof firstConvertedNum,
  typeof secondConvertedNum
);
//shorthand
let firstNumber = "102";
let secondNumber = "19.5";
let firstConvertedNumber = +firstNumber;
let secondConvertedNumber = +secondNumber;
console.log(
  typeof firstNumber,
  typeof secondNumber,
  typeof firstConvertedNumber,
  typeof secondConvertedNumber
);

Destructing assignment

//longhand
let user = { name: "ahmed", age: 29, email: "ahmed.m.web.dev@gmail.com" };
let userName = user.name;
let userAge = user.age;
console.log(userName, userAge);
//shorthand
let { name, age } = user;
console.log(name, age);

array.find shorthand

//longhand
const users = [
  {
    name: "ahmed",
    age: 20,
  },
  { name: "moahmed", age: 22 },
  { name: "diaa", age: 30 },
];
const findUserByName = (name) => {
  for (let start = 0; start < users.length; start++) {
    let user = users[start];
    if (user.name === name) {
      return user;
    }
  }
};
console.log(findUserByName("ahmed"));
//shorthand
let matchedUser = users.find((user) => {
  return user.name === "ahmed";
});
console.log(matchedUser);

Check element in array

//longhand
const users = ["ahmed", "diaa", "mohamed", "ali"];
if (users.indexOf("ahmed") > -1) {
  console.log("Item exists in array");
} else {
  console.log("Item not exist in array");
}
//shorthand
if (users.includes("ahmed")) {
  console.log("Exist");
} else {
  console.log("Not exist");
}

Object.entires()

This feature convert object to be and array

const user = {
  name: "Ahmed",
  email: "ahmed.m.web.dev@gmail.com",
  password: "1234",
};
let userArr = Object.entries(user);
console.log(userArr);

Object.values()

This feature returns an array contains all object values.

const user = {
  name: "Ahmed",
  email: "ahmed.m.web.dev@gmail.com",
  password: "1234",
};
let uservalues = Object.values(user);
console.log(uservalues);

Repeating a string multiple time

//longhand
let str = "";
for (let start = 0; start < 5; start++) {
  str += "test ";
}
console.log(str);
//shorthand
console.log("test ".repeat(5));

Find max and min values in array

const ages = [10, 62, 15, 12, 13];
console.log(Math.min(...ages));
console.log(Math.max(...ages));

Power shorthand

//longhand
console.log(Math.pow(2, 3));
//shorthand
console.log(2 ** 3);

Array functions

Fill function

/**
 * There are array of objects and we want to return all array elements as a string value of deleted
 */
//longhand
const users = [
  {
    id: 1,
    email: "a@a.a",
    password: "1234",
  },
  {
    id: 2,
    email: "b@b.b",
    password: "5678",
  },
  {
    id: 3,
    email: "c@c.c",
    password: "9101",
  },
];
//map does not affecting on source array
const convertedArr = users.map((user) => {
  return "deleted";
});
console.log(convertedArr);
//shorthand
//fill function affecting on source array
console.log(users.fill("deleted"));

array.flat()

/**
 * we have an array of arrays and strings
 * required return only one dimentional array
 */
//longhand
const tags = [
  "js",
  "DS",
  "PHP",
  ["HTML", "CSS", "Bootstrap"],
  "Git",
  ["Docker", "Kubernates"],
  "Redis",
];
const result = [];
tags.forEach((tag) => {
  tag instanceof Array ? result.push(...tag) : result.push(tag);
});
console.log(result);
//shorthand
console.log(tags.flat());

Finally I hope you are get some information and notes from this JS lab.

Subscribe to our Newsletter

Subscribe to tech-hour website to get all updates, new articles, new courses and projects. No spam ever. Unsubscribe at any time.