30 JavaScript Tricky HacksUncover Lesser-Known JavaScript Hacks for Smarter Coding

Welcome! Here’s a handpicked list of JavaScript hacks designed to make your code cleaner, smarter, and easier to manage. These tips will help you uncover the hidden capabilities of JavaScript and write more elegant code.

Table of Contents

  1. Convert Values to Boolean with !!
    Using double exclamation marks quickly turns any value into its boolean equivalent.
let truthy = !!'hello'; // true
let falsy = !!0; // false
  1. Set Defaults with Function Parameters
    Avoid undefined issues by assigning default values right in your function definition.
function greet(name = "Guest") {
    return `Hello, ${name}!`;
}
  1. Ternary Operator for Compact Conditions
    A quick alternative to if-else for assigning values based on conditions.
let status = age > 18 ? "Adult" : "Minor";
  1. Template Literals for Easier String Formatting
    Build strings with embedded expressions using backticks.
let product = "tea";
let cost = 5;
console.log(`A cup of ${product} costs $${cost}.`);
  1. Destructuring for Cleaner Variable Assignment
    Extract values directly from arrays or objects in a single line.
let [a, b] = [10, 20];
let {title, year} = {title: "Book", year: 2021};
  1. Spread Operator for Cloning Data
    Easily copy arrays or objects without affecting the original.
let arr = [1, 2, 3];
let copy = [...arr];
  1. Short-Circuit Logic for Conditional Execution
    Use && or || to conditionally run code or assign values.
isLoggedIn && showDashboard();
  1. Optional Chaining for Safe Access
    Avoid runtime errors when accessing deeply nested properties.
console.log(user?.profile?.email);
  1. Nullish Coalescing for Fallbacks
    Assign fallback values when the original is null or undefined.
let displayName = name ?? "Anonymous";
  1. Array Methods: map, filter, reduce
    Functional approaches to transform and analyze array data.
let data = [1, 2, 3];
let doubled = data.map(x => x * 2);
let evens = data.filter(x => x % 2 === 0);
let total = data.reduce((a, b) => a + b, 0);
  1. Tagged Template Literals for Custom String Handling
    Create custom string formatting by tagging templates with a function.
function emphasize(strings, ...values) {
    return strings.reduce((res, str, i) => res + str + `<em>${values[i] || ""}</em>`, "");
}
console.log(emphasize`Total is ${10}`);
  1. From Object to Array and Back
    Use Object.entries() and Object.fromEntries() to switch between formats.
let obj = { a: 1, b: 2 };
let arr = Object.entries(obj);
let rebuilt = Object.fromEntries(arr);
  1. Set for Unique Values
    Remove duplicates from an array using the Set object.
let unique = [...new Set([1, 2, 2, 3])];
  1. Dynamic Keys in Objects
    Assign keys dynamically using variables inside object literals.
let key = 'score';
let stats = { [key]: 100 };
  1. Function Currying with bind()
    Create partially applied functions for cleaner logic reuse.
function add(a, b) { return a + b; }
let addFive = add.bind(null, 5);
console.log(addFive(10)); // 15
  1. Create Arrays from Array-like Structures
    Turn NodeList or similar structures into real arrays.
let divs = document.querySelectorAll('div');
let arr = Array.from(divs);
  1. Simplified Iteration with for…of
    Use for...of to loop over iterable data types naturally.
for (let item of ['x', 'y']) {
    console.log(item);
}
  1. Run Promises Together with Promise.all()
    Handle multiple asynchronous operations simultaneously.
Promise.all([fetch(url1), fetch(url2)])
    .then(responses => console.log("Done!"));
  1. Gather Extra Function Arguments with Rest Parameters
    Access all arguments passed to a function as an array.
function logAll(...args) {
    args.forEach(arg => console.log(arg));
}
  1. Memoization to Optimize Repetitive Computations
    Cache function results to avoid repeated processing.
function memoize(fn) {
    const cache = {};
    return (x) => cache[x] ?? (cache[x] = fn(x));
}
  1. Swap Variables Using XOR
    Swap two values without a temporary variable.
let x = 3, y = 5;
x ^= y; y ^= x; x ^= y;
// x = 5, y = 3
  1. Flatten Nested Arrays with flat()
    Turn nested arrays into a single array with optional depth.
let flat = [1, [2, [3]]].flat(2);
  1. Unary Plus to Convert Strings to Numbers
    Convert string representations into numbers fast.
let number = +"42"; // 42
  1. Generate HTML Using Template Literals
    Embed logic directly inside HTML snippets.
let fruits = ['apple', 'pear'];
let list = `<ul>${fruits.map(f => `<li>${f}</li>`).join('')}</ul>`;
  1. Merge Objects Using Object.assign()
    Combine object properties into a new object.
let merged = Object.assign({}, {a: 1}, {b: 2});
  1. Set Defaults with Short-Circuiting
    Assign fallback values without explicit conditions.
let config = customConfig || defaultConfig;
  1. Access Properties Dynamically
    Use variables as property keys with bracket notation.
let prop = "email";
let userInfo = person[prop];
  1. Use includes() for Clearer Checks
    Check presence in an array more intuitively than indexOf.
if (colors.includes("red")) {
    console.log("Red is here!");
}
  1. Bind Context and Args with bind()
    Pre-set this and arguments for a reusable function.
function say(msg, punc) {
    return `${msg}, ${this.name}${punc}`;
}
let sayHi = say.bind({name: "Jane"}, "Hi");
console.log(sayHi("!")); // "Hi, Jane!"
  1. Make Objects Immutable with freeze()
    Lock objects to prevent modification.
let data = { status: "locked" };
Object.freeze(data);
data.status = "open"; // Ignored

These JavaScript hacks are perfect for leveling up your code quality, making your logic more concise, and boosting efficiency. Whether you’re optimizing performance or simplifying syntax, this list is your quick reference to writing smarter JavaScript.

What to read next