DEV Community

Cover image for 20 JavaScript Tricks for Improved Code Efficiency
Adam Mawlawi
Adam Mawlawi

Posted on

20 JavaScript Tricks for Improved Code Efficiency

1 - Using arrow functions to write concise, anonymous functions:

Instead of writing a function like this:

function add(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

You can use an arrow function to write it like this:

const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

2- Using the spread operator to easily copy arrays or objects:

To copy an array, you can use the spread operator like this:

const arr = [1, 2, 3];
const arrCopy = [...arr];
Enter fullscreen mode Exit fullscreen mode

To copy an object, you can do the same thing:

const obj = { name: "John" };
const objCopy = { ...obj };
Enter fullscreen mode Exit fullscreen mode

3- Using the ternary operator for concise conditional statements:

Instead of writing an if/else statement like this:

let result;
if (a > b) {
  result = "a is greater than b";
} else {
  result = "b is greater than a";
}

Enter fullscreen mode Exit fullscreen mode

You can use the ternary operator to write it like this:

const result = (a > b) ? "a is greater than b" : "b is greater than a";

Enter fullscreen mode Exit fullscreen mode

4- Using the for-of loop to easily iterate over arrays or objects:

Instead of writing a for loop like this:

const arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

Enter fullscreen mode Exit fullscreen mode

You can use the for-of loop to write it like this:

const arr = [1, 2, 3];
for (const item of arr) {
  console.log(item);
}

Enter fullscreen mode Exit fullscreen mode

**
5- Using destructuring to easily extract values from arrays or objects:**

Instead of writing code like this:

const arr = [1, 2, 3];
const a = arr[0];
const b = arr[1];
const c = arr[2];

Enter fullscreen mode Exit fullscreen mode

You can use destructuring to write it like this:

const arr = [1, 2, 3];
const [a, b, c] = arr;

Enter fullscreen mode Exit fullscreen mode

Or for an object:

const obj = { name: "John", age: 30 };
const name = obj.name;
const age = obj.age;

Enter fullscreen mode Exit fullscreen mode

You can use destructuring to write it like this:

const obj = { name: "John", age: 30 };
const { name, age } = obj;

Enter fullscreen mode Exit fullscreen mode

6- Using Array.map() to easily transform an array:

Instead of using a for loop to transform an array, you can use the Array.map() function like this:

const arr = [1, 2, 3];
const doubled = arr.map(num => num * 2); // [2, 4, 6]

Enter fullscreen mode Exit fullscreen mode

7- Using Array.filter() to easily filter an array:

Instead of using a for loop to filter an array, you can use the Array.filter() function like this:

const arr = [1, 2, 3, 4, 5];
const evenNumbers = arr.filter(num => num % 2 === 0); // [2, 4]

Enter fullscreen mode Exit fullscreen mode

8- Using Array.reduce() to easily reduce an array to a single value:

Instead of using a for loop to reduce an array to a single value, you can use the Array.reduce() function like this:

const arr = [1, 2, 3, 4];
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue); // 10

Enter fullscreen mode Exit fullscreen mode

9- Using try/catch blocks to handle errors:

Instead of writing code like this:

let result;
try {
  result = foo();
} catch (error) {
  console.log(error);
}

Enter fullscreen mode Exit fullscreen mode

You can write it like this:

try {
  const result = foo();
} catch (error) {
  console.log(error);
}

Enter fullscreen mode Exit fullscreen mode

10 - Using async/await to handle asynchronous code:

Instead of using Promise chains like this:

function getData() {
  return fetch("http://example.com/data")
    .then(response => response.json())
    .then(data => data.name)
    .catch(error => console.log(error));
}

Enter fullscreen mode Exit fullscreen mode

You can use async/await like this:

async function getData() {
  try {
    const response = await fetch("http://example.com/data");
    const data = await response.json();
    return data.name;
  } catch (error) {
    console.log(error);
  }
}

Enter fullscreen mode Exit fullscreen mode

11- Using Object.keys() to easily get an object's keys:
Instead of writing code like this:

const obj = { name: "John", age: 30 };
const keys = [];
for (const key in obj) {
  keys.push(key);
}

Enter fullscreen mode Exit fullscreen mode

You can use Object.keys() like this:

const obj = { name: "John", age: 30 };
const keys = Object.keys(obj); // ["name", "age"]

Enter fullscreen mode Exit fullscreen mode

12- Using Object.values() to easily get an object's values:
Instead of writing code like this:

const obj = { name: "John", age: 30 };
const values = [];
for (const key in obj) {
  values.push(obj[key]);
}

Enter fullscreen mode Exit fullscreen mode

You can use Object.values() like this:

const obj = { name: "John", age: 30 };
const values = Object.values(obj); // ["John", 30]

Enter fullscreen mode Exit fullscreen mode

13- Using Object.entries() to easily get an object's key-value pairs:

Instead of writing code like this:

const obj = { name: "John", age: 30 };
const entries = [];
for (const key in obj) {
  entries.push([key, obj[key]]);
}

Enter fullscreen mode Exit fullscreen mode

You can use Object.entries() like this:

const obj = { name: "John", age: 30 };
const entries = Object.entries(obj); // [["name", "John"], ["age", 30]]

Enter fullscreen mode Exit fullscreen mode

14- Using the JSON.parse() and JSON.stringify() functions to easily convert between JSON and JavaScript objects:

Instead of writing code like this:

const json = '{"name":"John","age":30}';
const obj = {};
obj.name = json.name;
obj.age = json.age;

Enter fullscreen mode Exit fullscreen mode

You can use JSON.parse() like this:

const json = '{"name":"John","age":30}';
const obj = JSON.parse(json);

Enter fullscreen mode Exit fullscreen mode

And to convert an object to JSON, you can use JSON.stringify() like this:

const obj = { name: "John", age: 30 };
const json = JSON.stringify(obj);

Enter fullscreen mode Exit fullscreen mode

15- Using Array.sort() to easily sort an array:

Instead of writing a function to sort an array, you can use the Array.sort() function like this:

const arr = [3, 1, 2];
const sorted = arr.sort((a, b) => a - b); // [1, 2, 3]

Enter fullscreen mode Exit fullscreen mode

16- Using the includes() method to check if an element exists in an array:

Instead of using indexOf() like this:

const arr = [1, 2, 3];
if (arr.indexOf(2) !== -1) {
  console.log("Element exists in array");
}

Enter fullscreen mode Exit fullscreen mode

You can use includes() like this:

const arr = [1, 2, 3];
if (arr.includes(2)) {
  console.log("Element exists in array");
}

Enter fullscreen mode Exit fullscreen mode

17- Using the padStart() and padEnd() methods to add padding to strings:

Instead of writing a function to add padding to a string, you can use padStart() or padEnd() like this:

const str = "abc";
const padded = str.padStart(5, "0"); // "00abc"

or

const str = "abc";
const padded = str.padEnd(5, "0"); // "abc00"

Enter fullscreen mode Exit fullscreen mode

18- Using the Object.assign() method to easily merge objects:

Instead of writing code like this:

const obj1 = { name: "John" };
const obj2 = { age: 30 };
const merged = {};
for (const key in obj1) {
  merged[key] = obj1[key];
}
for (const key in obj2) {
  merged[key] = obj2[key];
}

Enter fullscreen mode Exit fullscreen mode

You can use Object.assign() like this:

const obj1 = { name: "John" };
const obj2 = { age: 30 };
const merged = Object.assign({}, obj1, obj2);

Enter fullscreen mode Exit fullscreen mode

19- Using the spread operator to easily merge objects:

Instead of using Object.assign() like this:

const obj1 = { name: "John" };
const obj2 = { age: 30 };
const merged = Object.assign({}, obj1, obj2);

Enter fullscreen mode Exit fullscreen mode

You can use the spread operator like this:

const obj1 = { name: "John" };
const obj2 = { age: 30 };
const merged = { ...obj1, ...obj2 };

Enter fullscreen mode Exit fullscreen mode

20- Using the Set data structure to store unique values:

Instead of using an array and manually checking for duplicates, you can use the Set data structure like this:

const values = [1, 2, 3, 3, 4, 4];
const set = new Set(values); // Set {1, 2, 3, 4}

Enter fullscreen mode Exit fullscreen mode

You can then easily convert the Set back to an array using the spread operator:

const values = [1, 2, 3, 3, 4, 4];
const set = new Set(values);
const uniqueValues = [...set]; // [1, 2, 3, 4]

Enter fullscreen mode Exit fullscreen mode

In conclusion, there are many ways to improve the efficiency and simplicity of your JavaScript code. By using techniques like arrow functions, the spread operator, and async/await, you can write cleaner, more intuitive code that is easier to maintain and debug. Whether you are a beginner or an experienced developer, these tricks will help you to write better code and solve problems more efficiently.

Top comments (2)

Collapse
 
9opsec profile image
9opsec

Awesome list of tips!

Collapse
 
mradamus profile image
Adam Mawlawi

Thank you!