DEV Community

Cover image for 80 JavaScript Shortcuts Every Developer Should Know in 2025 (In-Depth)
Ahmed Niazy
Ahmed Niazy

Posted on

80 JavaScript Shortcuts Every Developer Should Know in 2025 (In-Depth)

Image description

1. Ternary Operator

What it does: Replaces simple if…else assignments.

// Instead of:
let status;
if (age >= 18) {
  status = 'adult';
} else {
  status = 'minor';
}
// Use:
const status = age >= 18 ? 'adult' : 'minor';
Enter fullscreen mode Exit fullscreen mode


`

Why you care: Keeps conditional logic in-line, reducing lines and making assignments more concise.


2. Default Parameters

What it does: Assigns defaults right in your function signature.

js
// Old way:
function greet(name) {
name = name || 'Guest';
console.log(
Hello, ${name});
}
// Modern:
function greet(name = 'Guest') {
console.log(
Hello, ${name});
}

Why: Eliminates boilerplate inside your function body; defaults apply only when the argument is undefined.


3. Arrow Functions

What it does: Provides shorter syntax and lexical this.

js
// Traditional:
const square = function(x) {
return x * x;
};
// Arrow:
const square = x => x * x;

Why: Fewer characters, and arrow functions inherit this from the enclosing scope, avoiding common binding pitfalls.


4. Object Destructuring

What it does: Extracts properties into local variables.

js
const user = { id: 1, name: 'Alice', role: 'admin' };
// Instead of:
const id = user.id;
const name = user.name;
// Use:
const { id, name } = user;

Why: Makes property extraction declarative and reduces repetitive user. prefixes.


5. Array Destructuring

What it does: Binds array elements to variables in one line.

js
const coords = [10, 20, 30];
// Traditional:
const x = coords[0];
const y = coords[1];
// Destructured:
const [x, y, z] = coords;

Why: Cleaner assignment and easy swapping of elements.


6. Template Literals

What it does: Interpolates variables and multi-line strings.

js
const user = 'Bob';
const msg =
Hello, ${user}!
Welcome back.;

Why: Eliminates awkward string concatenation and supports embedded expressions and line breaks.


7. Spread Operator

What it does: Expands iterable values or object properties.

js
const arr1 = [1,2];
const arr2 = [...arr1, 3]; // [1,2,3]
const obj1 = {a:1};
const obj2 = {...obj1, b:2}; // {a:1,b:2}

Why: Simplifies cloning and merging of arrays/objects without mutating originals.


8. Rest Parameters

What it does: Gathers remaining arguments into an array.

js
function sum(...nums) {
return nums.reduce((s,n) => s+n, 0);
}

Why: Replaces the old arguments object with a real array and clearer intent.


9. Optional Chaining

What it does: Safely accesses deep properties.

js
const street = user?.address?.street; // undefined if any link is nullish

Why: Prevents “Cannot read property of undefined” errors and removes many && checks.


10. Nullish Coalescing

What it does: Chooses the first non-null/undefined value.

js
const input = null;
const output = input ?? 'default'; // 'default'

Why: More precise fallback than ||, which also treats 0 or '' as falsey.


11. Logical AND Shortcut

What it does: Executes code only if a condition is true.

js
isReady && initialize();

Why: Shorter than if (isReady) initialize();.


12. Logical OR Assignment

What it does: Assigns only if the target is falsey.

js
user.name ||= 'Anonymous';

Why: Condenses if (!user.name) user.name = 'Anonymous';.


13. Logical AND Assignment

What it does: Assigns only if the target is truthy.

js
shouldReset &&= false;

Why: Short for if (shouldReset) shouldReset = false;.


14. Shorthand Property Names

What it does: Uses variable names as object keys automatically.

js
const name = 'Carol', age = 30;
const user = { name, age }; // {name:'Carol', age:30}

Why: No need to repeat name: name.


15. Computed Property Names

What it does: Uses expressions as object keys.

js
const key = 'role';
const user = { [key]: 'admin' }; // {role:'admin'}

Why: Dynamically build objects without mutating later.


16. for…of Loop

What it does: Iterates over iterable values.

js
for (const item of items) {
console.log(item);
}

Why: Cleaner than a numeric for when you just need each element.


17. Array.prototype.forEach

What it does: Calls a function for each element.

js
items.forEach(item => console.log(item));

Why: Declarative iteration without managing indices.


18. Array.prototype.map

What it does: Transforms each element into a new array.

js
const doubled = nums.map(n => n * 2);

Why: Clear intent for element-wise transformations.


19. Array.prototype.filter

What it does: Selects elements matching a predicate.

js
const evens = nums.filter(n => n % 2 === 0);

Why: Filters without loops and manual pushes.


20. Array.prototype.reduce

What it does: Aggregates array elements into a single value.

js
const total = nums.reduce((sum,n) => sum + n, 0);

Why: Powerful tool for sums, counts, or building complex results.


21. includes

What it does: Checks membership in arrays or strings.

js
if (colors.includes('red')) { /*…*/ }

Why: More readable than indexOf(...) !== -1.


22. Deduplicate with Set

What it does: Removes duplicates quickly.

js
const unique = [...new Set(arr)];

Why: One-liner for de-duplication that’s fast and expressive.


23. Object.entries

What it does: Returns [key, value] pairs.

js
for (const [k,v] of Object.entries(obj)) {
console.log(k, v);
}

Why: Easy iteration over both keys and values.


24. Object.values

What it does: Returns an array of values.

js
const vals = Object.values(obj);

Why: Simple list of values when keys aren’t needed.


25. Object.keys

What it does: Returns an array of keys.

js
const keys = Object.keys(obj);

Why: Basic building block for many object-level operations.


26. Method Chaining

What it does: Pipes results through multiple array methods.

js
const result = data
.filter(isActive)
.map(toDTO)
.reduce(accumulate, []);

Why: Processes data in a clear, declarative pipeline.


27. flat

What it does: Flattens nested arrays one level deep.

js
const flat = [[1,2], [3,4]].flat(); // [1,2,3,4]

Why: Avoids manual concat loops.


28. trim

What it does: Removes whitespace from both ends of a string.

js
const name = ' Alice '.trim(); // 'Alice'

Why: Cleans user input or formatted text easily.


29. padStart / padEnd

What it does: Pads a string to a given length.

js
'5'.padStart(2, '0'); // '05'

Why: Useful for time stamps or fixed-width formatting.


30. Intl.NumberFormat

What it does: Formats numbers per locale.

js
new Intl.NumberFormat('en-US').format(1234567); // "1,234,567"

Why: Handles thousands separators and decimal marks correctly for any locale.


31. Dynamic import

What it does: Loads modules on demand.

js
async function loadUtil() {
const util = await import('./util.js');
util.doSomething();
}

Why: Enables code-splitting and faster initial load.


32. Promise.all

What it does: Awaits multiple promises in parallel.

js
const [res1, res2] = await Promise.all([fetchA(), fetchB()]);

Why: Runs tasks concurrently instead of serially.


33. async/await

What it does: Writes asynchronous code like synchronous.

js
async function fetchData() {
const response = await fetch('/api/data');
return response.json();
}

Why: Removes nested .then chains and improves readability.


34. Optional Parameters with Defaults

What it does: Combine required and optional args.

js
function log(message, level = 'info') {
console[level](message);
}

Why: Flexible APIs without boilerplate checks.


35. Unary + for Number Conversion

What it does: Converts a string to a number.

js
const n = +'42'; // 42

Why: Shorter than parseInt or Number() when you’re sure input is numeric.


36. Double NOT for Boolean Conversion

What it does: Casts any value to a true/false.

js
const exists = !!value;

Why: Quickly normalizes values to boolean.


37. Swap Variables via Destructuring

What it does: Exchanges two variables without a temp.

js
[a, b] = [b, a];

Why: Elegant swap in one line.


38. Spread to Convert String to Array

What it does: Splits characters into an array.

js
const chars = [...'hello']; // ['h','e','l','l','o']

Why: Useful for per-character processing.


39. Shallow Clone Object

What it does: Copies top-level properties.

js
const clone = { ...original };

Why: Quick, non-deep copy to avoid mutating the source object.


40. Debounce Function

What it does: Delays function calls until a pause.

js
const debounce = (fn, delay = 300) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
};
// Usage:
window.addEventListener('resize',
debounce(() => console.log('Resized'), 200)
);

Why: Improves performance by batching rapid events (e.g., keystrokes, scrolls).


Advanced Shortcuts (41–80)

41. structuredClone for Deep Cloning

js
const deepCopy = structuredClone(complexObj);

Detail: Browser-native deep copy, handling arrays, objects, Maps, Sets, Dates, RegExps, and more—without JSON pitfalls.


42. Multi-value Nullish Coalescing

js
const firstValid = a ?? b ?? c;

Detail: Chains fallbacks—returns the first non-null/undefined value among several.


43. mapKeys & mapValues via Object.fromEntries

js
const upperKeys = Object.fromEntries(
Object.entries(obj).map(([k,v]) => [k.toUpperCase(), v])
);

Detail: Transform both keys and/or values declaratively in one pass.


44. groupBy with reduce

js
const grouped = items.reduce((acc, item) => {
const key = item.category;
(acc[key] ||= []).push(item);
return acc;
}, {});

Detail: Batches elements into arrays under computed group keys.


45. Chunking Arrays

js
function chunk(arr, size) {
return Array.from(
{ length: Math.ceil(arr.length / size) },
(_, i) => arr.slice(i * size, i * size + size)
);
}

Detail: Splits large arrays into smaller, fixed-length subarrays.


46. flatMap Combines map + flat

js
const letters = words.flatMap(word => [...word]);

Detail: Maps then flattens one level, in a single pass.


47. copyWithin In-place Array Copy

js
const a = [1,2,3,4,5];
a.copyWithin(0, 3, 5); // [4,5,3,4,5]

Detail: Efficiently overwrites portions without extra arrays.


48. find & findIndex

js
const odd = nums.find(n => n % 2);
const idx = nums.findIndex(n => n % 2);

Detail: Locates the first element (or its index) matching a predicate.


49. every & some

js
const allValid = arr.every(check);
const anyValid = arr.some(check);

Detail: Tests if all or at least one element satisfies a condition.


50. at() for Positive/Negative Indices

js
const last = arr.at(-1);

Detail: Cleaner than arr[arr.length - 1], supports negative indexing.


51. replaceAll for Strings

js
const sanitized = str.replaceAll('<', '&lt;');

Detail: Globally replace substrings without regex or /g.


52. matchAll for Regex Iteration

js
for (const m of 'a1b2'.matchAll(/\d/g)) {
console.log(m[0]);
}

Detail: Returns all matches with full detail (captures, indices).


53. URLSearchParams

js
const params = new URLSearchParams(window.location.search);
console.log(params.get('q'));

Detail: Parse and build query strings with a clean API.


54. Proxy for Intercepting Operations

js
const p = new Proxy(target, {
get(obj, prop) {
console.log(
Accessing ${prop});
return obj[prop];
}
});

Detail: Trap property access, assignment, enumeration, function calls, etc.


55. Reflect API for Meta-Programming

js
Reflect.set(obj, 'x', 10);

Detail: Lower-level operations that mirror Proxy traps and default behaviors.


56. WeakMap & WeakSet

js
const wm = new WeakMap();
wm.set(domNode, data);

Detail: Keys are weakly held, allowing garbage collection when no other references exist.


57. Intl.DateTimeFormat

js
new Intl.DateTimeFormat('ar-EG', {
dateStyle: 'full',
timeStyle: 'short'
}).format(new Date());

Detail: Locale-aware date/time formatting without external libs.


58. performance.now() for High-Res Timing

js
const start = performance.now();
// heavy computation
console.log(
Took ${performance.now() - start}ms);

Detail: Sub-millisecond precision timing in browsers.


59. console.table

js
console.table([{id:1,name:'A'}, {id:2,name:'B'}]);

Detail: Instantly visualizes arrays or objects as tables in DevTools.


60. import.meta.url

js
console.log(new URL('.', import.meta.url).pathname);

Detail: Retrieves current module location in ESM.


61. Dynamic require (Node.js)

js
const module = require(dynamicPath);

Detail: Load CommonJS modules based on runtime logic.


62. AbortController for Cancellable Fetch

js
const ctrl = new AbortController();
fetch(url, { signal: ctrl.signal });
ctrl.abort(); // cancels the request

Detail: Gracefully abort network requests or other async tasks.


63. Cache API (Service Worker)

js
caches.open('v1').then(cache => cache.addAll(['/','/app.js']));

Detail: Programmatic asset caching for offline apps and performance.


64. Web Workers

js
// main.js
const w = new Worker('worker.js');
w.postMessage(data);
// worker.js
self.onmessage = e => {
// heavy compute without blocking UI
};

Detail: Offloads CPU-intensive tasks to background threads.


65. SharedArrayBuffer

js
const shared = new SharedArrayBuffer(1024);

Detail: Share memory between workers with high performance.


66. WeakRef

js
const weak = new WeakRef(obj);

Detail: Holds a reference that doesn’t prevent GC—use carefully.


67. FinalizationRegistry

js
const reg = new FinalizationRegistry(token => {
console.log('Collected', token);
});
reg.register(obj, 'myToken');

Detail: Hook into GC events to clean up external resources.


68. Intl.Collator for Localized Sorting

js
const collator = new Intl.Collator('de', { sensitivity: 'base' });
['ä','a','z'].sort(collator.compare);

Detail: Correctly sorts strings per locale rules.


69. BigInt for Arbitrary-Precision Integers

js
const big = 9007199254740991n + 1n;

Detail: Beyond the Number.MAX_SAFE_INTEGER limit without precision loss.


70. Optional Catch Binding

js
try {
riskyOperation();
} catch {
console.error('Something failed');
}

Detail: Skip naming the error if you don’t need it.


71. Function Bind Shorthand (Proposal)

js
// In stage-2 environments:
const bound = obj::obj.method;

Detail: Experimental syntax for binding functions more tersely.


72. Logical Nullish Assignment

js
a ??= b;

Detail: Assign b only if a is null or undefined.


73. Promise.any

js
const firstSuccess = await Promise.any([p1, p2, p3]);

Detail: Resolves as soon as one promise fulfills, rejects only if all reject.


74. WeakRefs in Data Structures

Use WeakMap/WeakSet inside custom collections to avoid leaks when garbage collecting unused keys.


75. Top-Level await in ESM

js
// At module root in an ESM file
const data = await fetch('/api').then(r => r.json());

Detail: Simplifies module initialization code without wrapping in async functions.


76. ESLint Inline Disable

js
// eslint-disable-next-line no-console
console.log(user);

Detail: Bypass specific lint rules on a per-line basis.


77. JSDoc Type Hints for VSCode

js
/** @type {{id:number,name:string}} */
const user = { id:1, name:'Alice' };

Detail: Gets type-aware autocompletion in plain JS files.


78. Import Assertions (JSON Modules)

js
import data from './data.json' assert { type: 'json' };

Detail: Safely import JSON with ESM, preventing ambiguous formats.


79. Temporal API (Stage 3 / Polyfill)

js
import { Temporal } from '@js-temporal/polyfill';
const today = Temporal.Now.plainDateISO();

Detail: A robust replacement for the built-in Date object.


80. Intl.RelativeTimeFormat

js
new Intl.RelativeTimeFormat('en', { numeric: 'auto' })
.format(-1, 'day'); // “yesterday”

Detail: Displays human-friendly relative dates like “2 hours ago” or “in 3 days.”


Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.