Back to Blogs
blog featured image

Tips for Javascript

When we code, we tend to make long lines of code. There is no wrong with that, yet we need our code to be readable by others. Here are some tips and tricks.


Javascript Shorthands


1. If with multiple conditions

We can store multiple values in the array and we can use the array includes a method

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}


2. If true … else Shorthand

This is useful when you are assigning data to a variable. Thus we will utilize the Ternary Operator

// Longhand
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//or we can simply use
let test = x > 10;
console.log(test);


3. Null, Undefined, Empty Checks

We need to ensure that our inputs are not falsy values. This is useful when you are trapping or filtering the inputs from the users to prevent unwanted bugs.

// Longhand
if (first !== null || first !== undefined || first !== '') {
    let second = first;
}
// Shorthand
let second = first|| '';


4. Null Value checks and Assigning Default Value Undefined Value checks and Assigning Default Value

Some code needs a default value if the current value is null.

let first = null,
let second = first || '';
console.log("null check", test2); // output will be ""


5. Undefined Value checks and Assigning Default Value

Some code needs a default value if the current value is undefined.

let first= undefined,
let second = first || '';
console.log("undefined check", test2); // output will be ""



Bonus code snippets


Power Shorthand

//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8


Numeric Separators

//old syntax
let number = 98234567

//new syntax
let number = 98_234_567


avatar

Written By:

EJ Anton