Member-only story
28 JavaScript One-Liners every Senior Developer Needs to Know

1. Swapping Values Without a Temporary Variable
let a = 1, b = 2;
[a, b] = [b, a];
// Output: a = 2, b = 1
This one-liner uses array destructuring to swap the values of a
and b
without needing a temporary variable. It's a neat trick that makes your code cleaner and more concise. The [a, b] = [b, a]
syntax swaps their values by destructuring the array on the right-hand side and assigning it to the left-hand side.
2. Object Destructuring for Easier Data Access
const {name, age} = {name: 'John', age: 30};
// Output: name = 'John', age = 30
Here, object destructuring is used to extract name
and age
properties from an object directly into variables. This approach simplifies accessing object properties and enhances code readability.
3. Cloning Objects in a Snap
const originalObj = {name: 'Jane', age: 22};
const clonedObj = {...originalObj};
// Output: clonedObj = {name: 'Jane', age: 22}
The spread operator (...
) is utilized to create a shallow clone of originalObj
. This technique copies all enumerable own properties from the original object to a new object.
So can we not simply assign the old object to the new one?
const clonedObj = originalObj;
clonedObj.name = "George";
// Output: originalObj = {name: 'George', age: 22}
You can do this but clonedObj
will simply be a reference to originalObj
so if you tried modifying the name
property on clonedObj
you will actually be modifying the originalObj
!
4. Merging Objects Made Simple
const obj1 = {name: 'Jane'};
const obj2 = {age: 22};
const mergedObj = {...obj1, ...obj2};
// Output: mergedObj = {name: 'Jane', age: 22}
Similar to cloning, the spread operator is used to merge obj1
and obj2
into a new object. If there are overlapping properties, the properties from the last object will override the previous ones.
5. Cleaning Up Arrays
const arr = [0, 1, false, 2, '', 3];
const…