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
- 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
- Set Defaults with Function Parameters
Avoidundefined
issues by assigning default values right in your function definition.
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
- Ternary Operator for Compact Conditions
A quick alternative to if-else for assigning values based on conditions.
let status = age > 18 ? "Adult" : "Minor";
- 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}.`);
- 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};
- Spread Operator for Cloning Data
Easily copy arrays or objects without affecting the original.
let arr = [1, 2, 3];
let copy = [...arr];
- Short-Circuit Logic for Conditional Execution
Use&&
or||
to conditionally run code or assign values.
isLoggedIn && showDashboard();
- Optional Chaining for Safe Access
Avoid runtime errors when accessing deeply nested properties.
console.log(user?.profile?.email);
- Nullish Coalescing for Fallbacks
Assign fallback values when the original isnull
orundefined
.
let displayName = name ?? "Anonymous";
- 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);
- 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}`);
- From Object to Array and Back
UseObject.entries()
andObject.fromEntries()
to switch between formats.
let obj = { a: 1, b: 2 };
let arr = Object.entries(obj);
let rebuilt = Object.fromEntries(arr);
- Set for Unique Values
Remove duplicates from an array using theSet
object.
let unique = [...new Set([1, 2, 2, 3])];
- Dynamic Keys in Objects
Assign keys dynamically using variables inside object literals.
let key = 'score';
let stats = { [key]: 100 };
- 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
- Create Arrays from Array-like Structures
TurnNodeList
or similar structures into real arrays.
let divs = document.querySelectorAll('div');
let arr = Array.from(divs);
- Simplified Iteration with for…of
Usefor...of
to loop over iterable data types naturally.
for (let item of ['x', 'y']) {
console.log(item);
}
- Run Promises Together with Promise.all()
Handle multiple asynchronous operations simultaneously.
Promise.all([fetch(url1), fetch(url2)])
.then(responses => console.log("Done!"));
- 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));
}
- 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));
}
- 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
- Flatten Nested Arrays with flat()
Turn nested arrays into a single array with optional depth.
let flat = [1, [2, [3]]].flat(2);
- Unary Plus to Convert Strings to Numbers
Convert string representations into numbers fast.
let number = +"42"; // 42
- 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>`;
- Merge Objects Using Object.assign()
Combine object properties into a new object.
let merged = Object.assign({}, {a: 1}, {b: 2});
- Set Defaults with Short-Circuiting
Assign fallback values without explicit conditions.
let config = customConfig || defaultConfig;
- Access Properties Dynamically
Use variables as property keys with bracket notation.
let prop = "email";
let userInfo = person[prop];
- Use includes() for Clearer Checks
Check presence in an array more intuitively thanindexOf
.
if (colors.includes("red")) {
console.log("Red is here!");
}
- Bind Context and Args with bind()
Pre-setthis
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!"
- 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.