Swapna Kumar Panda Profile picture
| Tech Writer, Educator | prev. Architect | Python, JavaScript, SQL | Programming, Development, Databases, AI Tools, Remote Jobs | Building @JabardastDEV |

Oct 13, 2021, 12 tweets

🔥 9️⃣ Useful Hacks to simplify your JavaScript code

Follow these simple yet most useful hacks in your code. These are not only modern way of writing JS code but also minifies your code.

🧵 👇

We will cover,

1️⃣ Converting to Boolean
2️⃣ Converting to Number
3️⃣ Converting to String
4️⃣ Short-Circuit && and ||
5️⃣ Default Function Parameters
6️⃣ Nullish Coalescing Operator
7️⃣ Optional Chaining Operator
8️⃣ Array Resizing
9️⃣ Converting Array-Like to Array

1️⃣ Converting to Boolean

To convert any data to a Boolean type, use

→ Boolean function or,
→ !! operator

2️⃣ Converting to Number

To convert any data to a Number type, use

→ + operator or,
→ Number function or,
→ parseInt function

3️⃣ Converting to String

Use String function when you need to convert any data to a String type.

4️⃣ Short-Circuit && and ||

Instead of using traditional if-condition statements, try to use short-circuit && or, ||

Use this trick only when the expression inside "if" is just a one-liner expression or a simple function.

5️⃣ Default Function Parameters

To assign missing values on function parameters, instead of using || operator, use default function parameters.

6️⃣ Nullish Coalescing Operator

Instead of manually checking whether an input is either null or, undefined, use nullish coalescing operator (??).

7️⃣ Optional Chaining Operator

To avoid TypeError, instead of checking whether a property exists in an object manually, use optional chaining operator (?.)

8️⃣ Array Resizing

To remove few last elements from an array, simply modify the array's length property value. Items from the array will automatically be removed.

9️⃣ Converting Array-Like to Array

An Array-Like object is like an Array which has a length property and, can be iterated like an array.

E.g., arguments inside function body, a string object etc.

Use Array.from() or, spread operator to convert Array-Like to an Array.

That's it guys. Did you find these hacks useful and interesting?

Reply any additional hacks you are aware of. Share me your feedbacks as well.

See you in next 🧵 soon. 👋

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling