Home > Web Front-end > JS Tutorial > Simple tips help make code CLEAR and MAIN easier

Simple tips help make code CLEAR and MAIN easier

Barbara Streisand
Release: 2025-01-05 02:49:42
Original
839 people have browsed it

Những Tip đơn giản giúp đoạn code trở nên CLEAR và MAIN dễ hơn

With my own experience as a frontend programmer, I often build my own habits when writing code to help the code become flexible and improve capabilities. read as well as maintain the code.
These are all very simple but extremely useful tips that I want to share so you can completely understand at first sight.

Technique 1: Reduce the number of if-else statements

Every time we write something that uses more than 2 if-else, we need to consider whether there is a more optimal way to write the code. A simple example is as follows:

function getPrice(item) {
    if (item === 'iPHONE') return 1.0;
    else if (item === 'Samsung') return 0.5;
    else if (item === 'Xiaomi') return 0.75;
    // more ...
}

Copy after login
Copy after login
Copy after login

In this example I am writing a function to get the prices of phone brands, if I want to add the price of an oppo phone, I will need to add an if-else branch, or I want to modify the price of the phone. Xiaomi phone I will have to work hard to find the location of the Xiaomi phone in my jaw.
Writing code like this can make the code susceptible to errors such as being verbose, difficult to read, difficult to search and expand.
But don't worry I'll show you how to write it correctly without violating the DRY principle. We will use an object to store prices for products instead of using an if-else-if
chain.

function getPrice(item) {
    const prices = {
        'iPHONE': 1.0,
        'Samsung': 0.5,
        'Xiaomi': 0.75,
        'Oppo': 0.6
    };

    return prices[item] || 0;  // Trả về giá trị hoặc 0 nếu không có sản phẩm
}

Copy after login
Copy after login
Copy after login

In the above improved example, we can read the code more clearly, or when we want to change a price of a product, we do not need to change the core logic of the getPrice() function.

Technique 2: Pipelining technique reduces unnecessary number of loops

const phones = [
    { name: 'Apple', group: 1 },
    { name: 'Samsung', group: 2 },
    { name: 'Xiaomi', group: 1 },
    // more items...
];

const group1 = [];
for (let i = 0; i < phones .length; i++) {
    if (phones[i].group === 1) {
        group1.push(phones [i].name);
    }
}
Copy after login
Copy after login

This is a traditional way, you can use a for loop to loop through each element in the array and check which element meets the condition then add it to the result array.
Although the above method is not wrong, writing code like this can make the code more verbose and difficult to read. Instead we can use common functions like filter and map to help keep the code concise and enhance semantics.

const group1 = phones
    .filter(phone => phone.group === 1)
    .map(phone => phone.name);
Copy after login
Copy after login

Technique 3: Use find to replace duplicate loops

Continue with the phone segment example above. Then using find shows obvious convenience

function getPrice(item) {
    if (item === 'iPHONE') return 1.0;
    else if (item === 'Samsung') return 0.5;
    else if (item === 'Xiaomi') return 0.75;
    // more ...
}

Copy after login
Copy after login
Copy after login

This search method allows you to quickly locate the first element in the array that satisfies the provided condition, making the code much clearer than using traditional loops.

Technique 4: Use includes to replace redundant loops

When we need to check if an array contains a specific value, using includes can simplify your code instead of looping through the array to check for the existence of an element.

For example:

function getPrice(item) {
    const prices = {
        'iPHONE': 1.0,
        'Samsung': 0.5,
        'Xiaomi': 0.75,
        'Oppo': 0.6
    };

    return prices[item] || 0;  // Trả về giá trị hoặc 0 nếu không có sản phẩm
}

Copy after login
Copy after login
Copy after login

You just need to use includes:

const phones = [
    { name: 'Apple', group: 1 },
    { name: 'Samsung', group: 2 },
    { name: 'Xiaomi', group: 1 },
    // more items...
];

const group1 = [];
for (let i = 0; i < phones .length; i++) {
    if (phones[i].group === 1) {
        group1.push(phones [i].name);
    }
}
Copy after login
Copy after login

This method provides an elegant solution to the more cumbersome process of using traditional loops.

This feature is especially useful when dealing with arrays that you frequently need to check.

Technique 5: Use variables that return unique results

As far as I know, especially in compact functions, we can use consistent variable names for the returned results. This clarifies where the return value comes from and provides a standard variable naming convention that if someone else reads your code they can easily recognize it.

const group1 = phones
    .filter(phone => phone.group === 1)
    .map(phone => phone.name);
Copy after login
Copy after login

Technique 6: Maintain object integrity

While manipulating JSON data returned from the backend, we often process specific attributes individually in a key-value. This is even more obvious when we sometimes have cases that only use a few attributes. Many programmers tend to only extract the necessary properties for operations, this is the first method people think of, however this is a practical and ephemeral way of doing things.

When there is uncertainty about whether a function will need additional dependencies later, it is advisable to maintain the integrity of the entire object. For example, a function component can use icon and content but maybe title or date can be used later. Passing entire objects to function components instead of individual properties not only reduces the length of the props list but also enhances code readability and flexibility

function getPrice(item) {
    if (item === 'iPHONE') return 1.0;
    else if (item === 'Samsung') return 0.5;
    else if (item === 'Xiaomi') return 0.75;
    // more ...
}

Copy after login
Copy after login
Copy after login
function getPrice(item) {
    const prices = {
        'iPHONE': 1.0,
        'Samsung': 0.5,
        'Xiaomi': 0.75,
        'Oppo': 0.6
    };

    return prices[item] || 0;  // Trả về giá trị hoặc 0 nếu không có sản phẩm
}

Copy after login
Copy after login
Copy after login

? Final conclusion

The above JS coding techniques can improve the quality performance of your code, making it easier to read and maintain in the long run. So try these simple tips in your project and experience the improvements firsthand. Wish you happy coding !!!

The above is the detailed content of Simple tips help make code CLEAR and MAIN easier. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template