Javascript tricks and tips for efficient coding

Home » Programming » Javascript tricks and tips for efficient coding
javascipt-tricks-tips

Javascript tricks and tips for efficient coding

JavaScript can do a lot of things. Here is a list of tricks you should know to become a JavaScript pro.

 

1. Double exclamation ( !! )

The double exclamation mark (“!!”) serves as a shorthand to convert a value to its corresponding boolean equivalent. When applied to a value, “!!” returns true if the original value is truthy and false if it’s falsy. This technique is valuable for explicit boolean conversion. It can be particularly useful in scenarios where a clear boolean representation is needed.

let value = "Hello";
let booleanValue = !!value;

console.log(booleanValue); // true

 

2. Double tilde ( ~~ )

The “~” is a bitwise operator that quickly truncates decimal values to integers, making it more efficient than using “Math.floor” or “Math.round” for simple rounding tasks. The double tilde “~~” performs a faster floor operation, and its concise syntax aids readability. While “Math.floor” and “Math.round” involve function calls and additional computation, “~~” directly manipulates the binary representation, making it a preferred choice for rapid integer conversion in performance-sensitive scenarios.

let value = 12.123;

console.log(~~value); // 12

NOTE: For handling more complex rounding scenarios use the built-in Math functions.

 

3. Double question mark ( ?? )

The nullish coalescing operator “??” enables a concise and convenient handling of default values in situations requiring replacement of null or undefined values with a fallback. Unlike the logical OR operator (“||”), the nullish coalescing operator specifically checks for null or undefined. Additionally, it excludes other falsy values such as empty strings or zero.

const value = "Default";
let userInput;

let result = userInput ?? value;

console.log(result); // If userInput is null or undefined, it will be replaced with "Default".

 

4. Optional Chaining ( ?. )

The optional chaining operator “?.” allows you to safely access properties of an object without explicitly checking for the existence of each property in the chain. If any intermediate property is null or undefined, the entire expression evaluates to undefined, preventing potential errors.

const user = {
    city: "Mumbai",
    postalCode: 400001
};

const userCity = user?.city;
const userTel = user?.telephone;

console.log(userCity); // Mumbai
console.log(userTel); // undefined