DEV Community

Discussion on: Some cool JavaScript Shorthand that will make your code cleaner than your peer's

Collapse
 
haaxor1689 profile image
Maroš Beťko

Almost all of these I use pretty regularly and feel like every modern codebase should use them.
Here are some additional shorthands I use:

Range 1,2,3...n:

[...Array(n).keys()]
Enter fullscreen mode Exit fullscreen mode

Remove key from object:

const { key: _, obj } = object;
Enter fullscreen mode Exit fullscreen mode

Swap array items:

[arr[x], arr[y]] = [arr[y], arr[x]]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shubhracodes profile image
Shubhra Agarwal

Thank you for sharing this. I'm saving this comment for future reference

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited
[...Array(n).keys()]
Enter fullscreen mode Exit fullscreen mode

Gives you a range 0 to n-1. For a range 1 to n, you could use:

// This (much faster)...
Array.from({length:n},(_,i)=>i+1)

// Or maybe this (shorter but slower)...
[...Array(n).keys()].map(i=>i+1)
Enter fullscreen mode Exit fullscreen mode