๐ฆพ 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.