Hoai-Nho-Logo

/

Blog

AboutProjectsBlogContact

All topics

Architecture & Design

Architecture & Design
Discover cutting-edge architecture and design ideas. Explore innovative projects, modern interior design trends, sustainable architecture, and creative design solutions to inspire your next project.aws saa-c03
AWS

Explore best practices, tutorials, case studies, and insights on leveraging AWS’s vast ecosystem to build, deploy, and manage applications in the cloud

Design patterns

The Design Pattern category explores reusable solutions to common software design challenges, helping developers write efficient, maintainable, and scalable code

Docker
Explore essential Docker tutorials and resources. Find helpful tips, best practices, and tools to master containerization and improve your deployment workflow.
Security

The Security category focuses on best practices, tools, and frameworks essential for protecting applications, data, and infrastructure in an increasingly digital world

SSL license expired?

Ultimate Guide to Renewing SSL Certificates: Secure Your Website in 2024

Ensure your website stays secure! 🔒 Learn how to check, renew, and manage your SSL certificate to prevent security risks and downtime. Follow our step-by-step guide with best practices to keep your HTTPS protection active in 2024!

CSS

Database

Database
Find easy-to-follow guides on database SQL, NoSQL, PostgreSQL, and MySQL. Learn how to make databases that are fast and work well. Get tips to improve your skills. database
MySQL
Discover essential database guides covering SQL, NoSQL, and best practices. Get tips and performance benchmarks to improve your data management skills.
NoSQL
Discover essential database guides covering SQL, NoSQL, and best practices. Get tips and performance benchmarks to improve your data management skills.
PostgreSQL
Explore comprehensive PostgreSQL tutorials and resources. Find helpful tips, best practices, and performance benchmarks to enhance your database skills.
Search topic

LIKE vs Full-Text Search: SQL Performance and Use Cases

Explore the differences between SQL’s LIKE operator and Full-Text Search. Learn their syntax, performance, use cases, and advanced features for optimizing database queries

Generation

Interview Question

NodeJS

NodeJS
Explore beginner to advanced tutorials on JavaScript and TypeScript. Find helpful tips, best practices, and tools to create powerful web applications. typescript_vs_javascript
Javascript/Typescript
Learn JavaScript and TypeScript with easy guides. Discover tips, best practices, and tools to build efficient web applications quickly.
tripple-cache

🚀 Triple-Layered Web Caching Strategy: How Memory, IndexedDB and HTTP Cache Improved Speed by 96%

Discover how to accelerate your website through our powerful triple-layered caching strategy combining Memory Cache, IndexedDB, and HTTP Cache. Detailed guidance from theory to practice helps reduce page load time by up to 96%, improve user experience, and optimize performance across all devices.


© 2025 Hoai Nho. All rights reserved.

ContactGitHubLinkedIn
  1. Home
  2. /Blog
  3. /10 Advanced JavaScript Tricks Every Developer Should Master

10 Advanced JavaScript Tricks Every Developer Should Master

Discover 10 advanced JavaScript techniques, including tail call optimization, currying, proxies, debouncing, throttling, and more. Learn how to write efficient, maintainable, and optimized code for modern web development.

JS-tricks
Hoài Nhớ@hoainho
December 20, 2024
|

2 min read

|

169 Views

Share:

Enhancing your JavaScript skills involves mastering both fundamental and advanced techniques. Building upon the foundational tricks, here are additional advanced JavaScript techniques that can further optimize your code and development workflow:

1. Tail Call Optimization

In JavaScript, functions can call themselves recursively. Tail call optimization allows recursive functions to execute without increasing the call stack size, preventing stack overflow errors. This optimization occurs when a function returns the result of calling another function as its final action.

function factorial(n, acc = 1) {
  if (n <= 1) return acc;
  return factorial(n - 1, n * acc);
}
console.log(factorial(5)); // 120

2. Proxy Objects for Dynamic Behavior

The Proxy object enables you to create dynamic behaviors for fundamental operations on objects, such as property lookup, assignment, enumeration, and function invocation.

const handler = {
  get: (target, prop) => {
    return prop in target ? target[prop] : `Property ${prop} not found`;
  },
};
const person = { name: 'Alice' };
const proxyPerson = new Proxy(person, handler);
console.log(proxyPerson.name); // Alice
console.log(proxyPerson.age);  // Property age not found

3. Currying Functions

Currying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. This technique allows for the creation of more modular and reusable functions.

const add = (a) => (b) => a + b;
const addFive = add(5);
console.log(addFive(3)); // 8

4. Debouncing and Throttling

Debouncing and throttling are techniques to control the frequency of function execution, particularly useful in scenarios like handling window resizing or scroll events.

• Debouncing: Ensures a function is executed only after a specified delay has elapsed since the last time it was invoked.

const debounce = (func, delay) => {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func(...args), delay);
  };
};


• Throttling: Ensures a function is executed at most once in a specified time interval.

const throttle = (func, limit) => {
  let inThrottle;
  return (...args) => {
    if (!inThrottle) {
      func(...args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
};

5. Using Map and Set for Data Management

Map and Set are built-in objects that provide efficient ways to manage collections of data.

• Map: Stores key-value pairs and remembers the original insertion order of the keys.

const map = new Map();
map.set('name', 'Alice');
console.log(map.get('name')); // Alice


• Set: Stores unique values of any type, whether primitive values or object references.

const set = new Set([1, 2, 3, 3]);
console.log(set); // Set { 1, 2, 3 }

6. Asynchronous Iteration with for await…of

When dealing with asynchronous data sources, for await…of allows you to iterate over promises sequentially.

async function processUrls(urls) {
  for await (const url of urls) {
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
  }
}

7. Using WeakMap and WeakSet for Memory Management

WeakMap and WeakSet are similar to Map and Set, but they allow for garbage collection of their keys and values when there are no other references to them, aiding in efficient memory management.

let obj = {};
const weakMap = new WeakMap();
weakMap.set(obj, 'value');
// obj can be garbage collected when no other references exist

8. Template Literals for Multi-line Strings and Expressions

Template literals provide an easy way to create multi-line strings and embed expressions within strings.

const name = 'Alice';
const greeting = `Hello, ${name}!
Welcome to the JavaScript world.`;
console.log(greeting);

9. Optional Chaining and Nullish Coalescing

Optional chaining (?.) allows safe access to deeply nested object properties, and nullish coalescing (??) provides default values when dealing with null or undefined.

const user = { profile: { name: 'Alice' } };
console.log(user.profile?.name); // Alice
console.log(user.profile?.age ?? 'Age not available'); // Age not available

10. Using Promise.allSettled() for Multiple Promises

Promise.allSettled() waits for all promises to settle (either fulfilled or rejected) and returns their results, which is useful when you want to handle multiple asynchronous operations and proceed after all of them have completed, regardless of their outcome.

const promises = [
  fetch('/api/user'),
  fetch('/api/posts'),
  fetch('/api/comments'),
];
Promise.allSettled(promises).then((results) =>
  results.forEach((result) => {
    if (result.status === 'fulfilled') {
      console.log('Fulfilled:', result.value);
    } else {
      console.log('Rejected:', result.reason);
    }
  })
);

By incorporating these advanced techniques into your JavaScript development, you can write more efficient, maintainable, and robust code, enhancing both performance and readability.


Tags:
JavasciptJS Tricks
Written by

author
Hoài Nhớ

Hoài Nhớ

@Hoài Nhớ
JavasciptJS Tricks

Table of Contents

    References posts

    🚀 Triple-Layered Web Caching Strategy: How Memory, IndexedDB and HTTP Cache Improved Speed by 96%

    Discover how to accelerate your website through our powerful triple-layered caching strategy combining Memory Cache, IndexedDB, and HTTP Cache. Detailed guidance from theory to practice helps reduce page load time by up to 96%, improve user experience, and optimize performance across all devices.

    Hoài Nhớ
    Redux Thunk vs Redux Saga: A Deep Dive into Strengths, Weaknesses, and Hidden Pitfalls

    This article explores the core differences between Redux Thunk and Redux Saga, highlighting their strengths, weaknesses, and best use cases. Whether you’re building a small application or managing complex asynchronous workflows, understanding these middleware options will help you make the right choice for your Redux architecture.

    Hoài Nhớ
    🚀 React 19 Deep Dive: A Senior Engineer’s Practical Guide to New Hooks

    An in-depth analysis of React 19’s new hooks from a 20-year veteran engineer’s perspective. Learn practical implementation strategies, best practices, and real-world use cases for use(), useFormState(), useFormStatus(), and useOptimistic() hooks.

    Hoài Nhớ
    Related Posts

    tripple-cache
    FrontendOptimizationIndexedDB
    🚀 Triple-Layered Web Caching Strategy: How Memory, IndexedDB and HTTP Cache Improved Speed by 96%

    Discover how to accelerate your website through our powerful triple-layered caching strategy combining Memory Cache, IndexedDB, and HTTP Cache. Detailed guidance from theory to practice helps reduce page load time by up to 96%, improve user experience, and optimize performance across all devices.

    Hoài Nhớ
    Redux Thunk and Saga
    Redux SagaRedux Thunk
    Redux Thunk vs Redux Saga: A Deep Dive into Strengths, Weaknesses, and Hidden Pitfalls

    This article explores the core differences between Redux Thunk and Redux Saga, highlighting their strengths, weaknesses, and best use cases. Whether you’re building a small application or managing complex asynchronous workflows, understanding these middleware options will help you make the right choice for your Redux architecture.

    Hoài Nhớ
    Breakings NewsReact19
    🚀 React 19 Deep Dive: A Senior Engineer’s Practical Guide to New Hooks

    An in-depth analysis of React 19’s new hooks from a 20-year veteran engineer’s perspective. Learn practical implementation strategies, best practices, and real-world use cases for use(), useFormState(), useFormStatus(), and useOptimistic() hooks.

    Hoài Nhớ

    Subscribe to our newsletter

    Get the latest posts delivered right to your inbox