Modern Javascript Tricks Every Developer Should Use

Javascript is one of the coolest and most used language out there. It has been few decades since the Javascript came into existence and we have seen a lot enhancement in javascript time to time.

Over the period of time, lot of new cool features have been added into the Javascript. Javascript developer are so overwhelmed with learning and working on the new Library, Framework like React, Angular etc that they sometime ignore the new features added in javascript and do not use the full power of the most powerful language out there. In this Post, i will be discussing the few of the javascript cool features or tricks that will be useful for beginner, intermediate or expert developer.

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 user = {
  id: 1,
  name: 'Ishant Gaurav',
  ...(condition && { age: 30})   // conditionally add age property
};

console.log(user); // will print the user object with age property

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: 'Ishant Gaurav',
  ...(false), // evaluates to false
};
// spreading false has no effect on the object
console.log(person); // { id: 1, name: 'Ishant Gaurav' }

2. Short-Circuit Evaluation

The ternary operator is a quick way to write simple (and sometimes not-so-simple) conditional statements, like these:

x > 100 ? 'Greater Than 100' : 'Less Than 100';
x > 100 ? (x > 200 ? 'Greater Than 200' : 'Between 100-200') : 'Less Than 100';

But sometimes even the ternary operator is more complicated than necessary. Instead, we can use the ‘and’ && and ‘or’ || logical operators to evaluate certain expressions in an even more concise way. This is often called ‘short-circuiting’ or ‘short-circuit evaluation’.

 We can use && operator to return the first falsy value.  If every operand evaluates to true , the last evaluated expression will be returned.

let one = 1, two = 2, three = 3;
console.log(one && two && three); // Result: 3
console.log(0 && null); // Result: 0

Using || will return the first true or ‘truthy’ value. If every operand evaluates to false , the last evaluated expression will be returned.

let one = 1, two = 2, three = 3;
console.log(one || two || three); // Result: 1
console.log(0 || null); // Result: null

Simplify the if condition using && operator:

if (this.state.data) {
  return <div>Showing data</div>
} 

Above code can be simplified by using && operator as below :

return this.state.data && <div>Showing data</div>

3. Check if a Property Exists in an Object

We can use the in keyword to check whether a property exists in a JavaScript Object?

const user = { name: 'Ishant Gaurav', salary: 100 };

if('salary' in user) {
  console.log("Salary Property exist in user object");
}

if('age' in user) {
  console.log("age");
}

4. Dynamic Property Names in Objects

Many times in our project we have referenced object property dynamically to fetch its value or to check whether it exist or not as below :

const keyName = 'name';
console.log(user[keyName]); // returns 'Ishant'

We can also use the same kind to dynamically add the property name in the object. Just use the ['key_name'] notation to add the properties:

const dynamic = 'age';
var user = {
  name: 'Ishant',
  [dynamic]: '30'
}
console.log(user); // { name: 'Ishant', age: '30' }

5. NULL check using Nullish Coalescing, ?? Operator

The ?? operator is useful when you want to check whether a variable is null or undefined. It returns the right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

const foo = null ?? 'Hello';
console.log(foo); // returns 'Hello'

const bar = 'Not null' ?? 'Hello';
console.log(bar); // returns 'Not null'

const baz = 0 ?? 'Hello';
console.log(baz); // returns 0

In the third example, 0 is returned because even though 0 is considered falsy in JavaScript, it is not null or undefined. You may think that we can use the || operator here but there is a difference between these two:

const cannotBeZero = 0 || 5;
console.log(cannotBeZero); // returns 5

const canBeZero = 0 ?? 5;
console.log(canBeZero); // returns 0

6. Optional chaining (?.)

Do you also hate errors like TypeError: Cannot read property ‘foo’ of nullThis is a pain in the neck for every JavaSript developer. Optional chaining was introduced just to solve this. Let’s take a look:

const book = { id:1, title: 'Title', author: null };

// normally, you would do this
console.log(book.author.age) // throws error
console.log(book.author && book.author.age); // returns null (no error)

// with optional chaining
console.log(book.author?.age); // returns undefined

// or deep optional chaining
console.log(book.author?.address?.city); // returns undefined

7. Destructuring and Renaming Object Property With : Notation

We can destructure the object property and rename it using the : notation as below:

const user = { id: 1, name: 'Ishant Gaurav' };
const { name: userName } = user;
console.log(userName); // returns 'Ishant Gaurav'

8. Boolean Conversion Using the !! Operator

The !! operator can be used to quickly convert the result of an expression into a boolean true or false. Here’s how:

const greeting = 'Hello there!';
console.log(!!greeting) // returns true

const noGreeting = '';
console.log(!!noGreeting); // returns false

9. String and Integer Conversions

Quickly convert a string to a number using the + operator like this:

const stringNumer = '123';
console.log(+stringNumer); // returns integer  123
console.log(typeof +stringNumer); // returns 'number'

These type-conversions are super-handy but they have less clarity and code readability. So, you may have to think before using them in production.

10. Check Falsy Values in an Array

You must be familiar with filtersome, and every array methods. But you should also know that you can just the Boolean method to test for truthy values

const myArray = [null, false, 'Hello', undefined, 0];

// filter falsy values
const filtered = myArray.filter(Boolean);
console.log(filtered); // returns ['Hello']

// check if at least one value is truthy
const anyTruthy = myArray.some(Boolean);
console.log(anyTruthy); // returns true

// check if all values are truthy
const allTruthy = myArray.every(Boolean);
console.log(allTruthy); // returns false

Here’s how it works. As we know that these array methods take a callback function, so we pass Boolean as a callback function. Boolean itself takes an argument and returns true or false based on the truthiness of the argument. So we can say that this:

myArray.filter(val => Boolean(val));

Is the same as this:

myArray.filter(Boolean);

11. Flattening Arrays of Arrays

There is a method flat on the prototype Array that lets you make a single array from an array of arrays:

const myArray = [{ id: 1 }, [{ id: 2 }], [{ id: 3 }]];
const flattedArray = myArray.flat(); // returns [ { id: 1 }, { id: 2 }, { id: 3 } ]

12. Filter Unique Values

The Set object type was introduced in ES6, and along with ..., the ‘spread’ operator, we can use it to create a new array with only the unique values.

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Result: [1, 2, 3, 5]

This trick works for arrays containing primitive types: undefinednullbooleanstring and number . (If you had an array containing objects, functions or additional arrays, you’d need a different approach!)

Conclusion

We saw some of the new cool features of javascript which are actually handy but generally not much into the practice. Few of the above tricks are very helpful and can make your coding much easy whereas for few of them you need to be cautious while using them in production code.

This is all from this Post, if you have any other thoughts or found something wrong, please comment below.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s