20 Essential JavaScript Tricks to Write Cleaner, Faster Code

Discover 20 practical JavaScript techniques—from using let/const and destructuring to async/await and debouncing—that help you write more concise, efficient, and maintainable code while improving overall development workflow.

21CTO
21CTO
21CTO
20 Essential JavaScript Tricks to Write Cleaner, Faster Code

JavaScript is a powerful, versatile language, but mastering it requires effort; this guide compiles 20 commonly used JavaScript tricks to write cleaner, more efficient code and improve development workflow.

1. Use let and const instead of var

Avoid var; use let and const for block scope and to prevent hoisting issues.

let name = 'John';
const age = 30;

2. Destructuring Assignment

Extract values from arrays or object properties into separate variables.

const person = { name: 'Jane', age: 25 };
const { name, age } = person;

const numbers = [1, 2, 3];
const [first, second] = numbers;

3. Template Literals

Insert variables and expressions into strings easily.

const name = 'John';
const greeting = `Hello, ${name}!`;

4. Default Parameters

Set default values for function parameters to avoid undefined errors.

function greet(name = 'Guest') {
  return `Hello, ${name}!`;
}

5. Arrow Functions

Provide concise syntax for functions.

const add = (a, b) => a + b;

6. Spread Operator

Expand elements of iterables (arrays) or properties of objects.

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];

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

7. Rest Parameters

Collect an indefinite number of arguments into an array.

function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

8. Short‑Circuit Evaluation (&& and ||)

Use logical operators for default values and conditional expressions.

const user = { name: 'John' };
const name = user.name || 'Guest';

const isAdmin = user.isAdmin && 'Admin';

9. Object Property Shorthand

When variable names match property names, use shorthand syntax.

const name = 'John';
const age = 30;
const person = { name, age };

10. Optional Chaining (?.)

Safely access deeply nested properties without explicit checks.

const user = { name: 'John', address: { city: 'New York' } };
const city = user.address?.city;

11. Nullish Coalescing (??)

Return the right‑hand operand when the left is null or undefined.

const user = { name: 'John' };
const name = user.name ?? 'Guest';

12. Array Methods: map(), filter(), reduce()

Perform common operations on arrays in a functional style.

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
const evens = numbers.filter(num => num % 2 === 0);
const sum = numbers.reduce((total, num) => total + num, 0);

13. Promise Chains and Async/Await

Handle asynchronous operations with cleaner syntax.

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

14. Debounce and Throttle

Optimize performance by limiting how often functions are invoked.

function debounce(func, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
}
window.addEventListener('resize', debounce(() => { console.log('Resized'); }, 300));

function throttle(func, limit) {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}
window.addEventListener('scroll', throttle(() => { console.log('Scrolled'); }, 300));

15. Use for...of Loops

Iterate over arrays, strings, and other iterables with readable syntax.

const numbers = [1, 2, 3, 4, 5];
for (const number of numbers) {
  console.log(number);
}

16. Clone Objects and Arrays

Use the spread operator or Object.assign() to create shallow copies.

const original = { name: 'John', age: 30 };
const clone = { ...original };

const arr = [1, 2, 3];
const arrClone = [...arr];

17. Dynamic Property Names

Compute property names to set object keys dynamically.

const propName = 'age';
const person = {
  name: 'John',
  [propName]: 30
};

18. setTimeout and setInterval

Schedule code execution after a delay or at regular intervals.

setTimeout(() => { console.log('This runs after 2 seconds'); }, 2000);

const intervalId = setInterval(() => { console.log('This runs every 3 seconds'); }, 3000);
// To clear the interval
clearInterval(intervalId);

19. String Methods: includes(), startsWith(), endsWith()

Perform common string operations with modern methods.

const str = 'Hello, World!';
console.log(str.includes('World')); // true
console.log(str.startsWith('Hello')); // true
console.log(str.endsWith('!')); // true

20. Effective Console Debugging

Leverage various console methods for better debugging.

console.log('Simple log');
console.warn('This is a warning');
console.error('This is an error');
console.table([{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }]);
console.group('Group');
console.log('Message 1');
console.log('Message 2');
console.groupEnd();
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendJavaScriptcodingTips
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.