10 One‑Line JavaScript Tricks to Simplify Everyday Coding
This article presents ten concise, one‑line JavaScript techniques—from array deduplication and object merging to random value generation and deep copying—that streamline common development tasks, improve code readability, and boost efficiency for front‑end developers.
In JavaScript development we often encounter seemingly complex problems that can be solved with concise code. Below are ten one‑line JavaScript tricks that address common challenges.
1. Array deduplication
const uniqueArray = [...new Set(array)];This line uses the uniqueness of Set to deduplicate an array in a single step, more concise and efficient than traditional loops.
2. Convert object property values to array
const values = Object.values(object);Directly obtains all property values of an object and converts them into an array, avoiding manual iteration.
3. Generate random boolean
const randomBoolean = Math.random() >= 0.5;Creates a random boolean value, useful for decisions that require randomness.
4. Get random element from array
const randomElement = array[Math.floor(Math.random() * array.length)];Selects a random element from an array, suitable for lotteries, random displays, etc.
5. Check if variable is null or undefined
const isNullOrUndefined = value == null;Checks whether a variable is null or undefined, simplifying conditional checks.
6. Convert string to number
const num = +"42";Uses the unary plus operator to quickly convert a string to a number, more concise than parseInt().
7. Round to specific decimal places
const toFixed = num => Math.round(num * 100) / 100; // keep two decimalsA more reliable method than toFixed() for retaining decimal places, avoiding rounding issues.
8. Merge objects
const mergedObject = {...obj1, ...obj2};Uses the spread operator to quickly merge multiple objects; later properties overwrite earlier ones with the same name.
9. Get URL parameters
const params = Object.fromEntries(new URLSearchParams(window.location.search));Parses query parameters from the URL in one line, returning an object containing all parameters.
10. Deep copy an object
const deepCopy = JSON.parse(JSON.stringify(object));Although limited (cannot handle functions or circular references), this is the simplest deep‑copy method for most JSON‑compatible data structures.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
