Member-only story

10 Modern JavaScript Tricks Every Developer Should Use

Tips for writing short, concise, and clean JavaScript code

Haseeb Anwar
Better Programming
5 min readJun 15, 2021

You must have seen the guy in the picture above. He simplifies everyday things — and that’s exactly what we are going to do with JavaScript in this article.

JavaScript has a lot of cool features that most beginner and intermediate developers don’t know. I’ve picked out 10 hacks that I use in my everyday JavaScript projects.

1. Conditionally Add Properties to Object

We can use the spread operator, ..., to quickly add properties to a JavaScript object conditionally.

const condition = true;const person = {
id: 1,
name: 'John Doe',
...(condition && { age: 16 }),
};

The && operator returns the last evaluated expression if every operand evaluates to true. So an object { age: 16 } is returned, which is then spread to be part of the person object.

If condtion is false then JavaScript will do something like this:

const person = {
id: 1,
name: 'John Doe',
...(false), // evaluates to false
};
// spreading false has no effect on the object
console.log(person); // { id: 1, name: 'John Doe' }

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (16)

What are your thoughts?