DEV Community


Posted on

JavaScript Tricks You Didn’t Know Existed

JavaScript is a versatile and powerful language, but even seasoned developers can be surprised by some of its lesser-known features and tricks. In this article, we'll explore a few JavaScript tricks that can make your code more elegant, efficient, and fun to write. Whether you’re a beginner or an experienced developer, these tips will help you get the most out of JavaScript in 2024.

1. Optional Chaining Operator (?.)

Have you ever encountered undefined or null errors when trying to access deeply nested properties in an object? The optional chaining operator (?.) can help you safely navigate these structures.


const user = {
  profile: {
    name: 'Alice',
    address: {
      city: 'Wonderland'

console.log(user.profile?.address?.city); // Output: Wonderland
console.log(user.profile?.phone?.number); // Output: undefined (no error)
Enter fullscreen mode Exit fullscreen mode

The ?. operator checks if the property before it is null or undefined. If it is, the expression short-circuits and returns undefined instead of throwing an error. This is particularly useful when dealing with data from APIs or complex objects.

2. Nullish Coalescing Operator (??)

The nullish coalescing operator (??) is a handy tool for providing default values. Unlike the logical OR (||) operator, it only considers null and undefined as nullish.


const username = null;
const displayName = username ?? 'Guest';

console.log(displayName); // Output: Guest
Enter fullscreen mode Exit fullscreen mode

In this example, username is null, so displayName takes the default value 'Guest'. If username were an empty string or 0, displayName would still be set to those values since they are not considered nullish.

3. Dynamic Imports

Dynamic imports allow you to load JavaScript modules on demand, which can improve performance by reducing the initial load time of your application.


document.getElementById('loadModule').addEventListener('click', async () => {
  const module = await import('./module.js');
Enter fullscreen mode Exit fullscreen mode

In this example, the import function is called when the button is clicked. This asynchronously loads the module, which can then be used as needed. This technique is great for optimizing applications, especially when dealing with large libraries or infrequently used features.

4. Destructuring with Default Values

Destructuring is a powerful feature in JavaScript, and you can enhance it by providing default values.


const user = { name: 'Bob' };
const { name, age = 30 } = user;

console.log(name); // Output: Bob
console.log(age); // Output: 30
Enter fullscreen mode Exit fullscreen mode

In this example, the age property is not defined in the user object, so it takes the default value of 30. This is a clean and concise way to handle default values when destructuring objects.

5. Short-Circuit Evaluation

Short-circuit evaluation allows you to execute code based on the truthiness of expressions using logical AND (&&) and OR (||) operators.


const isLoggedIn = true;
const user = isLoggedIn && { name: 'Jane' };

console.log(user); // Output: { name: 'Jane' }

const isAdmin = false;
const adminName = isAdmin || 'No Admin';

console.log(adminName); // Output: No Admin
Enter fullscreen mode Exit fullscreen mode

In the first example, user is only assigned the object if isLoggedIn is true. In the second example, adminName is assigned 'No Admin' because isAdmin is false.

6. Tagged Template Literals

Tagged template literals allow you to parse template literals with a function. This can be used for various purposes, such as internationalization or custom formatting.


function highlight(strings, ...values) {
  return strings.reduce((result, string, i) => 
    `${result}${string}<strong>${values[i] || ''}</strong>`, '');

const name = 'Alice';
const city = 'Wonderland';

console.log(highlight`Hello ${name}, welcome to ${city}!`);
// Output: Hello <strong>Alice</strong>, welcome to <strong>Wonderland</strong>!
Enter fullscreen mode Exit fullscreen mode

The highlight function processes the template literal, wrapping the interpolated values in <strong> tags. This is a powerful feature for creating custom string processing functions.

7. Object Property Shorthand

When creating objects, you can use the shorthand syntax to include properties whose names are the same as variables.


const name = 'Charlie';
const age = 25;

const user = { name, age };

console.log(user); // Output: { name: 'Charlie', age: 25 }
Enter fullscreen mode Exit fullscreen mode

Instead of writing { name: name, age: age }, you can simply write { name, age }. This shorthand makes your code cleaner and more concise.

8. Promise.allSettled

Promise.allSettled is a relatively new addition to JavaScript that returns a promise that resolves after all of the given promises have either resolved or rejected.


const promises = [
  Promise.resolve('Another Success')

Promise.allSettled(promises).then(results => {
  results.forEach(result => console.log(result.status));
// Output: "fulfilled", "rejected", "fulfilled"
Enter fullscreen mode Exit fullscreen mode

Promise.allSettled is useful when you want to know the outcome of all promises, regardless of whether they were resolved or rejected. It provides an array of objects with the status and value or reason for each promise.


JavaScript is full of hidden gems and powerful features that can make your code more elegant and efficient. By incorporating these tricks into your development workflow, you can write cleaner, more robust code. Keep exploring and experimenting with JavaScript to discover even more ways to enhance your projects!

Feel free to share your own favorite JavaScript tricks in the comments below. Happy coding! 🚀

Twitter: @delia_code


Top comments (0)