Swapna Kumar Panda Profile picture
| Tech Writer, Educator | Python, Java, JavaScript, SQL | DSA, Development | Free Resources, AI Tools | Other Version: @therealswapna | Building @JabardastDEV |

Jan 31, 2022, 14 tweets

๐Ÿฆพ 11 Modern JavaScript Hacks

โ‡ฉ

๐Ÿ“‹ Table of Contents

โžŠ Conversion to Number
โž‹ Conversion to Boolean
โžŒ Conversion to String
โž Complex String
โžŽ Short Circuit && / ||
โž Nullish Check
โž Default Value
โž‘ Default Function Parameter
โž’ Optional Chaining
โž“ Array Resizing
โžŠโžŠ Function Rest Parameter

โžŠ Conversion to Number

To convert any data to a Number type, use

โ‡ฅ Unary "+" operator
โ‡ฅ Number function
โ‡ฅ parseInt function

โž‹ Conversion to Boolean

To convert any data to a Boolean type, use

โ‡ฅ Boolean function
โ‡ฅ !! operator (Double Bang Operator)

โžŒ Conversion to String

Are you converting a value to a String like below? Remember, it's faulty.

โ‡ฅ '' + input

Instead use String() function.

โž Complex String

Are you forming a String using multiple concatenation operators? Remember, it's difficult to write and hard to read.

โ‡ฅ 'Hello ' + fName + ' ' + lName

The modern approach is to use String Template Literals.

โ‡ฅ `Hello ${fName} ${lName}'

โžŽ Short Circuit && / ||

Are you still using "if" statements for one-liners?

โ‡ฅ if (hungry) eat()

The modern approach in such scenarios is to use Short-Circuits.

โ‡ฅ hungry && eat()

โž Nullish Check

How do you check Nullish values?

The modern and most effective way is doing it using "Nullish Coalescing Operator" (??)

โž Default Value

How do you assign value to a variable if it's missing?

โ‡ฅ x || (x = 10)
โ‡ฅ y ?? (y = 10)

The modern approach of doing it is

โ‡ฅ x ||= 10
โ‡ฅ y ??= 10

โž‘ Default Function Parameter

Do you often check if a function parameter is missing its value and manually assign a value to it?

The modern approach is to use default function parameters.

โž’ Optional Chaining

To avoid TypeError, instead of checking whether a property exists in an object manually, use "Optional Chaining Operator" (?.)

โž“ 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.

โžŠโžŠ Function Rest Parameter

Are you using "arguments" variable to manipulate your function parameters? The modern approach is to use a "rest parameter".

End of ๐Ÿงต

Are you looking for modern tricks for web development? I am sharing those on HTML/CSS, JavaScript and React regularly.

If you are interested, Follow me โœ…

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