JavaScript Minimal Coding Tips

In this post, we’ll be discussing some coding tips to help make your JavaScript code more minimal. By following these tips, you can improve the performance of your code and make it more readable.

Boolean Casting

When programming in JavaScript, you may occasionally need to convert a non-Boolean value to a Boolean (true or false). This is called “casting”. There are several ways to do this, which we will explore in the below demo.

Long
const string = 'string';
const hasValue = Boolean(string);
console.log(hasValue); // true
Short
const string = 'string';
const hasValue = !!string;
console.log(hasValue); // true

Get more details from freecodecamp.org

Optional chaining

In JavaScript, optional chaining is a feature that allows you to access deep data structures without having to check if each level exists. This can be helpful when working with data that might not be well-formed, or when you want to avoid the overhead of null checks.

Long
const hasValid Postcode = u =>
u &&
u.address &&
u.address.postcode &&
u.address.postcode.valid
Short
const hasValidPostcode = u => u?.address?.postcode?.valid

Get more details in developer.mozilla.org

Nullish Coalescing

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is either null or undefined and otherwise returns its left-hand side operand.

Long
const addId = (user, id) => {
    user.id = id !== null && id !== undefined ?
        id :
        "Unknown"
    return user
}
Short
const addId = (user, id) => {
    user.id = id ? ? "Unknown"
    return user
}

Get more details in developer.mozilla.org

Destructuring

Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. It can be used in locations that receive data (such as the left-hand side of an assignment). The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.

Long
const save = params => {
        saveData(
            params.name,
            params.email,
            params.dob
        }
Short
const save = ({
    name,
    email,
    dob
}) => {
    saveData(name, email, dob)
}

Get more details in developer.mozilla.org

W3TWEAKS
Latest posts by W3TWEAKS (see all)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *