JavaScript is full of small features that can make your code cleaner, shorter, and easier to maintain.
Here are 15 JavaScript tricks I use almost every week while building web applications with Next.js and React.
Hopefully, you'll find at least a few that make your coding life easier.
1. Remove Duplicate Values
const numbers = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(numbers)];
console.log(unique);
// [1,2,3,4,5]
2. Optional Chaining
Instead of writing:
if (user && user.address && user.address.city) {
console.log(user.address.city);
}
Use:
console.log(user?.address?.city);
Much cleaner and safer.
3. Nullish Coalescing Operator
const username = null;
console.log(username ?? "Guest");
Output:
Guest
Unlike ||, this only replaces null or undefined.
4. Object Destructuring
Instead of:
const name = user.name;
const age = user.age;
Write:
const { name, age } = user;
5. Swap Variables
Old way:
let a = 10;
let b = 20;
const temp = a;
a = b;
b = temp;
Modern JavaScript:
[a, b] = [b, a];
6. Copy Objects
const newUser = {
...user,
};
No loops required.
7. Merge Objects
const user = {
name: "John",
};
const details = {
age: 25,
};
const result = {
...user,
...details,
};
console.log(result);
8. Remove Falsy Values
const arr = [0, "", false, "Hello", undefined, 5, null];
const clean = arr.filter(Boolean);
console.log(clean);
Output:
["Hello",5]
9. Flatten Arrays
const arr = [[1], [2], [3]];
console.log(arr.flat());
Output:
[1,2,3]
10. Dynamic Property Names
const key = "email";
const user = {
[key]: "john@example.com",
};
console.log(user);
11. Convert Object into Array
const user = {
name: "John",
age: 25,
};
console.log(Object.entries(user));
Output:
[
["name", "John"],
["age", 25],
];
12. Promise.all()
Instead of waiting one request after another:
await getUsers();
await getPosts();
await getComments();
Run everything together:
await Promise.all([
getUsers(),
getPosts(),
getComments(),
]);
Much faster.
13. Get the Last Element
Instead of:
arr[arr.length - 1];
Use:
arr.at(-1);
Cleaner and easier to read.
14. Generate a UUID
const id = crypto.randomUUID();
console.log(id);
Example:
4c5d7d67-2a58-4b76-a52d-5b43c672b16f
Perfect for temporary IDs.
15. Use const by Default
Instead of writing:
var total = 100;
Use:
const total = 100;
Only use let when the value needs to change.
Avoid var in modern JavaScript.
šÆ Bonus Tip
Use Prettier and ESLint in every JavaScript project.
Good formatting and linting save hours of debugging and make your code much easier to maintain.
Final Thoughts
JavaScript continues to evolve, and even small language features can significantly improve the quality of your code.
These tricks may seem simple individually, but together they help write cleaner, more maintainable, and less error-prone applications.
If you have a favorite JavaScript trick that isn't on this list, share it in the comments. I'd love to learn something new!
Happy Coding! š
Tags:
#javascript #webdev #programming #beginners
Top comments (0)