Top 20 JavaScript Tricks and Tips for Every Developer 🚀
Dipak Ahirav

Dipak Ahirav @dipakahirav

About: Full Stack Developer | Angular & MEAN Stack Specialist | Tech Enthusiast | I’ve garnered over 3K+ reactions | 350+ comments | 325K+ readers | 170+ posts | 43K+ followers

Location:
Pune, Maharastra
Joined:
Apr 26, 2024

Top 20 JavaScript Tricks and Tips for Every Developer 🚀

Publish Date: Jul 29 '24
318 30

JavaScript is a versatile and powerful language, but it can also be tricky to master. Here are 20 JavaScript tricks and tips that every developer should know to write cleaner, more efficient code and improve their development workflow. 🌟

please subscribe to my YouTube channel to support my channel and get more web development tutorials.

1. Use let and const Instead of var 🚫

Avoid using var to declare variables. Instead, use let and const to ensure block-scoping and avoid hoisting issues.

Example:

let name = 'John';
const age = 30;
Enter fullscreen mode Exit fullscreen mode

2. Destructuring Assignment 🌟

Destructuring allows you to extract values from arrays or properties from objects into distinct variables.

Example:

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

const numbers = [1, 2, 3];
const [first, second] = numbers;
Enter fullscreen mode Exit fullscreen mode

3. Template Literals 📜

Template literals provide an easy way to interpolate variables and expressions into strings.

Example:

const name = 'John';
const greeting = `Hello, ${name}!`;
Enter fullscreen mode Exit fullscreen mode

4. Default Parameters 🛠️

Set default values for function parameters to avoid undefined errors.

Example:

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

5. Arrow Functions 🎯

Arrow functions provide a concise syntax and lexically bind the this value.

Example:

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

6. Spread Operator ... 🌐

The spread operator allows you to expand elements of an iterable (like an array) or properties of an object.

Example:

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

const obj1 = { name: 'John' };
const obj2 = { ...obj1, age: 30 };
Enter fullscreen mode Exit fullscreen mode

7. Rest Parameters ... 🌟

Rest parameters allow you to represent an indefinite number of arguments as an array.

Example:

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

8. Short-Circuit Evaluation && and || 🛠️

Use short-circuit evaluation for conditional expressions and default values.

Example:

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

const isAdmin = user.isAdmin && 'Admin';
Enter fullscreen mode Exit fullscreen mode

9. Object Property Shorthand 🚀

Use shorthand syntax to create objects when the property name and variable name are the same.

Example:

const name = 'John';
const age = 30;
const person = { name, age };
Enter fullscreen mode Exit fullscreen mode

10. Optional Chaining ?. 🌐

Optional chaining allows you to safely access deeply nested properties without having to check if each reference is valid.

Example:

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

11. Nullish Coalescing ?? 🌟

Nullish coalescing (??) provides a way to return the right-hand operand when the left-hand operand is null or undefined.

Example:

const user = { name: 'John' };
const name = user.name ?? 'Guest';
Enter fullscreen mode Exit fullscreen mode

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

Use array methods like map(), filter(), and reduce() to perform common operations on arrays in a functional way.

Example:

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);
Enter fullscreen mode Exit fullscreen mode

13. Promise Chaining and Async/Await 🎯

Handle asynchronous operations using Promises and the async/await syntax for cleaner, more readable code.

Example with Promises:

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

Example with Async/Await:

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

14. Debouncing and Throttling 🌟

Optimize performance by debouncing and throttling functions that are called frequently, such as during scroll or resize events.

Debouncing Example:

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));
Enter fullscreen mode Exit fullscreen mode

Throttling Example:

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));
Enter fullscreen mode Exit fullscreen mode

15. Using for...of for Iteration 🚀

Use the for...of loop for more readable iteration over arrays, strings, and other iterable objects.

Example:

const numbers = [1, 2, 3, 4, 5];

for (const number of numbers) {
  console.log(number);
}
Enter fullscreen mode Exit fullscreen mode

16. Cloning Objects and Arrays 🛠️

Use the spread operator or Object.assign() to clone objects and arrays.

Example:

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

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

17. Dynamic Property Names 🌟

Use computed property names to dynamically set object properties.

Example:

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

18. Using setTimeout and setInterval 🎯

Schedule code execution using setTimeout and setInterval.

Example:

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);
Enter fullscreen mode Exit fullscreen mode

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

Use modern string methods to perform common string operations.

Example:

const str = 'Hello, World!';

console.log(str.includes('World')); // true
console.log(str.startsWith('Hello')); // true
console.log(str.endsWith('!')); // true
Enter fullscreen mode Exit fullscreen mode

20. Using console Effectively for Debugging 🛠️

Leverage various console methods for more effective debugging.

Example:

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();
Enter fullscreen mode Exit fullscreen mode

Start Your JavaScript Journey

If you're new to JavaScript or want a refresher, visit my blog on BuyMeACoffee to get started with the basics.

👉 Introduction to JavaScript: Your First Steps in Coding

Support My Work

If you enjoy my content and want to support my work, consider buying me a coffee! Your support helps me continue creating valuable content for the developer community.

Series Index

Part Title Link
1 Ditch Passwords: Add Facial Recognition to Your Website with FACEIO Read
2 The Ultimate Git Command Cheatsheet Read
3 Top 12 JavaScript Resources for Learning and Mastery Read
4 Angular vs. React: A Comprehensive Comparison Read
5 Top 10 JavaScript Best Practices for Writing Clean Code Read
6 Top 20 JavaScript Tricks and Tips for Every Developer 🚀 Read
7 8 Exciting New JavaScript Concepts You Need to Know Read
8 Top 7 Tips for Managing State in JavaScript Applications Read
9 🔒 Essential Node.js Security Best Practices Read
10 10 Best Practices for Optimizing Angular Performance Read
11 Top 10 React Performance Optimization Techniques Read
12 Top 15 JavaScript Projects to Boost Your Portfolio Read
13 6 Repositories To Master Node.js Read
14 Best 6 Repositories To Master Next.js Read
15 Top 5 JavaScript Libraries for Building Interactive UI Read
16 Top 3 JavaScript Concepts Every Developer Should Know Read
17 20 Ways to Improve Node.js Performance at Scale Read
18 Boost Your Node.js App Performance with Compression Middleware Read
19 Understanding Dijkstra's Algorithm: A Step-by-Step Guide Read
20 Understanding NPM and NVM: Essential Tools for Node.js Development Read

Mastering these JavaScript tricks and tips will help you write cleaner, more efficient code and improve your development workflow. Happy coding! ✨

Follow and Subscribe:

Comments 30 total

  • Samuel
    SamuelJul 29, 2024

    This is a great article! However, you probably shouldn't use the spread operator to clone nested objects. Objects are references so a shallow clone with the spread operator will clone nested refs, not the objects. You should use structuredClone() instead.

  • manimaran
    manimaranJul 30, 2024

    Great articles. Simpler and neat explanation.

  • Medison Chikuta
    Medison ChikutaJul 30, 2024

    Hey, a new to code and am learning JavaScript.

  • Tomas Stveracek
    Tomas StveracekJul 30, 2024

    Great short summary!

  • kince marando
    kince marandoJul 30, 2024

    Great insight links , and eye opening for junior and Senior develops.!
    Kindly thanks

  • Michalis Papamichael
    Michalis PapamichaelJul 30, 2024

    informative article

  • Maximilian Lenhardt
    Maximilian LenhardtJul 30, 2024

    I use everything except Short-Circuit Evaluation, I believe that's a feature to avoid. It's just too different from other programming languages out there and it requires implicit knowledge of what evaluates to truthy or falsy in JavaScript, which is a weird concept in itself (I generally think that loading up special values of classes meaning something else is a bad idea).

  • KC
    KCJul 31, 2024

    Can we also promote using TypeScript as a superscript of JS?

  • Olanrewaju
    OlanrewajuJul 31, 2024

    Thanks for this👍💯, very helpful

  • Игорь Виноградов
    Игорь ВиноградовJul 31, 2024

    Just to note - provided examples for object cloning is not deep clone. Which means that if the object has nested arrays/objects - they will still have references to the original objects/arrays. lodash library has "cloneDeep" method which can achieve deep cloning

    • Akshay Bachhav
      Akshay BachhavAug 1, 2024

      Correct. Shallow cloning copies references. Use Lodash cloneDeep for true copies.

  • Lemon Confidence
    Lemon ConfidenceJul 31, 2024

    Neat explanation.

    I really like the concept of nullish coalescing.

    Some concepts I rarely use :⁠-⁠|

  • technology
    technologyAug 1, 2024

    Your article on JavaScript is excellent!

    However, it seems to be missing a section on completely hiding JavaScript from the browser. If you’re interested, we can either add this content to your post or provide the text for you to include.

  • Akshay Bachhav
    Akshay BachhavAug 1, 2024

    Concept of nullish coalescing explained very clean... Thanks

  • eneasmarin
    eneasmarinAug 1, 2024

    Great one. So satisfying to realize that I am using most of them, but still some good ones to include in my work

  • Renterra
    RenterraAug 2, 2024

    Cool!

  • Teenyfy
    TeenyfyAug 14, 2024

    Teenyfy is a distinct advantage! With its capacity to create shorter websites, it's ideally suited for upgrading content and supporting client commitment. Smoothed out plan and productive usefulness make Teenyfy an unquestionable requirement for current site improvement. Contact us for more!

  • Ashley D
    Ashley DSep 4, 2024

    Super helpful @dipakahirav! I like the series you made- you are a wonderful teacher. Currently working on a React JS project myself, and I found these tips really helpful!
    🚀

    • Dipak Ahirav
      Dipak AhiravSep 4, 2024

      Thank you so much for kind words. Means alot.

  • Syed Muhammad Ali Raza
    Syed Muhammad Ali RazaSep 9, 2024

    informative article

  • JohnsonSureDotDev
    JohnsonSureDotDevSep 26, 2024

    As a newbie I've now got something worth knowing,big thanks to you bro

  • Dandoy Jeans
    Dandoy JeansOct 9, 2024

    Good read! Thank you!

Add comment