Member-only story
10 Modern JavaScript Tricks Every Developer Should Use
Tips for writing short, concise, and clean JavaScript code

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' }
2. Check if a Property Exists in an Object
Do you know that we can use the in
keyword to check whether a property exists in a JavaScript Object?
const person = { name: 'John Doe', salary: 1000 };console.log('salary' in person); // returns true
console.log('age' in person); // returns false
3. Dynamic Property Names in Objects
Setting an object property with a dynamic key is simple. Just use the ['key_name']
notation to add the properties:
const dynamic = 'flavour';var item = {
name: 'Biscuit',
[dynamic]: 'Chocolate'
}console.log(item); // { name: 'Biscuit', flavour: 'Chocolate' }
The same trick can also be used to reference object properties with a dynamic key: