Forget Ternary Operator

I had seen many cases where we use ternary conditionals, on assigning a value to a variable. But this can be simplified by using Nullish Coalescing. Look at the snippet below showing comparisons. Just FYI, this checks if x is null or undefined.

const val = x ? x : y;

// Simplified version
const val = x ?? y;

Short-Circuit Evaluation

This one is a little closer to Nullish Coalescing in a sense. Many devs use this in React world. Ensure you use it correctly - check below for a confusing usage.

// This will render 0 if items is empty array!!
{
  items.length && <Items items={items} />;
}

// This works like - if a is truthy, result will be a, which is why it's rendering 0 in the previous statement. If a is falsy, result will be b.
const result = a && b;

Loop labels

Often less used feature, but if you have nested loops, and you want to exit any loop based on a condition, use labels for the loops.

outer: for (let i = 0; i < 10; i++>) {
    inner: for (let j = 0; j < 25; j++) {
        if (j === 10) {
            break outer;  // exits all loops
        }
    }
}

Deep Cloning Objects

A very very simple naive solution for deep cloning objects is to stringify them, and then parse that string back to JSON.

const deepCopy = JSON.parse(JSON.stringify(objSource));

Import Anything Anywhere!!

With ES6 modules, importing any modules is like using a simple promise, just like you might be making an API call from anywhere in the application. With this, imagine the possibilities - importing all files, importing conditionally etc..

const module = await import("./sample.js");

Flattening Arrays

Arrays now have native method flat which takes in value for how deep it should go flattening the array. With a small snippet below, you can flatten any level of nested array.!

const deepArr = [1, [2, 3], [4, [5, [6]]]];
const flatArray = deepArr.flat(Infinity);

Will share some more, as I keep learning! Have fun!