You've got a few, five bad js-coded habits

Keywords: Javascript Front-end

For more articles, please pay attention to WeChat Public Number: Front End css and js Dry

Have you ever felt this way when reading js code?

  • You hardly understand what the code means?

  • Does the code use a lot of outdated JavaScript techniques?

  • Naming and coding style more casual? These are signs of bad coding habits.

This article lists five common bad coding habits in JavaScript. More importantly, this paper gives practical suggestions on how to break these habits.

1. Do not use implicit type conversion

JavaScript is a weakly typed language. This is an advantage if used properly because it provides flexibility.
Most operators + - * / == (excluding ===) use implicit type conversions when working with different types of data. The if (condition) {...}, while(condition) {...} statement implicitly converts the condition to a Boolean value.
The following examples rely on implicit type conversions. I bet you'll be confused:

console.log("2" + "1"); // => "21"

console.log("2" - "1"); // => 1

console.log('' == 0); // => true

console.log(true == []); // -> false

console.log(true == ![]); // -> false

Overdependence on implicit type conversions is a bad habit. First, it makes your code unstable in some cases. Second, it makes it more difficult to reproduce and fix bug s.

Here is a function to get the properties of an object. If the property does not exist, the function returns a default value:

function getProp(object, propertyName, defaultValue) {

if (!object[propertyName]) {

    return defaultValue;

}

return object[propertyName];

}

const hero = {

    name: 'Batman',

    isVillian: false

};

console.log(getProp(hero, 'name', 'Unknown')); // => 'Batman'

getProp() reads the value of the name property, which is "Batman".

What happens if you access the isVillian property:

console.log(getProp(hero, 'isVillian', true)); // => true

This is an error. The function getProp() returns the error true even if the hero's isVillian attribute is false.
This is because the existence of an attribute depends on implicit conversion to a Boolean value through if (!object[propertyName]) {...}. Such errors are hard to find. To fix this function, you need to clarify the type of data.

function getPropFixed(object, propertyName, defaultValue) {

if (object[propertyName] === undefined) {

    return defaultValue;

}

return object[propertyName];

}

const hero = {

    name: 'Batman',

    isVillian: false

};

console.log(getPropFixed(hero, 'isVillian', true)); // => false

object[propertyName] === undefined Verifies whether the operation result of the property accessor is undefined.
Side note: Section 4.It is recommended that undefined be avoided directly. Therefore, the in operator can be used to improve the above scheme:

function getPropFixedBetter(object, propertyName, defaultValue) {

    if (!(propertyName in object)) {

        return defaultValue;

    }

    return object[propertyName];

}

Suggestion: Do not use implicit type conversions whenever possible. Conversely, make sure that variables and function parameters always have the same type. Use explicit type conversion if necessary.

Best Practices List:

  • Always perform comparisons using the strict equality operator===

  • Do not use the loose equality operator==

  • Addition operator operand1+operand2: Both operands should be numbers or strings

  • Arithmetic Operator - * /%: Both operands should be numbers

  • if (condition) {...}, while (condition) {...} and so on: condition should be a Boolean value

  • You might say that this method requires more code to write... that's true! But with clear methods, you can control the behavior of your code. This also increases readability.

2. Don't use outdated JavaScript techniques

The interesting thing about JavaScript is that its founders didn't expect the language to become so popular.

JavaScript-based applications are growing more complex than languages. This forces developers to use javaScript hacks to implement functionality.

A classic example is to search an array for an element. Use array.indexOf(item)!== - 1 to monitor the existence of elements.
ECMAScript 2015 and later versions are becoming more and more powerful. You can safely refactor many hacks with new language features.

Refactoring array.indexOf(item) using the ES2015 method array.include(item)!= - 1.

3. Do not pollute the function scope

Until ES2015, js variables were function scoped, so you might have developed the bad habit of declaring all variables in a function scoped way. Take an example:

function someFunc(array) {

    var index, item, length = array.length;

    /*

    * Lots of code

    */

    for (index = 0; index < length; index++) {

        item = array[index];

        // Use `item`

    }

    return someResult;

}

The variables index, item, and length are function scoped. However, these variables can pollute the function scope because they are only necessary within the for() block scope.

With the introduction of the block-scope variable declaration keywords let and const, we should limit the life cycle of variables as much as possible.

Let's fix the above code:

function someFunc(array) {

    /*

    * Lots of code

    */

    const length = array.length;

    for (let index = 0; index < length; index++) {

        const item = array[index];

        // Use `item`

    }

    return someResult;

}

The index and item variables exist only in the for() loop block scope. length moves near its point of use.
The refactored code is easier to understand because variables are not scattered throughout the function. They exist near the point of use.

Define variables within the block scope they use:
if block scope

//  Bad practice
let message;
// ...
if (notFound) {
  message = 'Item not found';
  // Use `message`
}
//  Good practices
if (notFound) {
  const message = 'Item not found';
  // Use `message`
}

for block scope

//  Bad practice
let item;
for (item of array) {
  // Use `item`
}
//  Good practices
for (const item of array) {
  // Use `item`
}

4. Avoid undefined and null as much as possible

Unassigned variables are automatically evaluated as undefined. For example:

let count;

console.log(count); // => undefined

const hero = {

    name: 'Batman'

};

console.log(hero.city); // => undefined

The count variable is defined but has not been initialized with a value. JavaScript is implicitly assigned to it undefined. Unfined is also returned when accessing the nonexistent attribute hero.city.
Why is it a bad habit to use undefined directly? Because when we compare directly with undefined, it is possible that we are dealing with variables in an uninitialized state.
Variables, object properties, arrays must be initialized with values before they can be used!
JavaScript provides many ways to avoid direct comparisons with undefine.

Does the property exist:

//  Bad practice
const object = {
  prop: 'value'
};
if (object.nonExistingProp === undefined) {
  // ...
}

//  Good practices
const object = {
  prop: 'value'
};
if ('nonExistingProp' in object) {
  // ...
}

Object Default Properties

//  Bad practice
function foo(options) {
  if (object.optionalProp1 === undefined) {
    object.optionalProp1 = 'Default value 1';
  }
  // ...
}

//  Good practices
function foo(options) {
  const defaultProps = {
    optionalProp1: 'Default value 1'
  };
  options = {
    ...defaultProps,
    ...options
  };
  // ...
}

Function default parameters

//  Bad practice
function foo(param1, param2) {
  if (param2 === undefined) {
    param2 = 'Some default value';
  }
  // ...
}


//  Good practices
function foo(param1, param2 = 'Some default value') {
  // ...
}

You should try to avoid returning null from a function and, more importantly, calling a function with null as an argument. Once null appears on your call stack, you must check that the variable is null in every function that may access null. This is cumbersome and error prone, as follows:

function bar(something) {

    if (something) {

        return foo({ value: 'Some value' });

    } else {

        return foo(null);

    }

}

function foo(options) {

    let value = null;

    if (options !== null) {

        value = options.value;

        // ...

    }

    return value;

}

Try to write code that does not involve null values. An alternative is the try/catch mechanism.
Tony Hoare, the inventor of ALGOL, once said:

I call it a billion-dollar error... I'm designing the first comprehensive type system for references in object-oriented languages. But I can't resist the temptation of null to quote just because it's easy to do. This has led to countless errors, bugs and system crashes that have caused $1 billion in pain and damage over the past four decades.

"The most serious error in computer science" This article delves into why null impairs code quality.

5. Don't use arbitrary coding style

What is more daunting than reading code with random encoding? You never know what will happen! What if the code base contains different coding styles for many developers? Various types of people graffiti walls.

image.png

Require the same coding style for the entire team and application code base. It improves the readability of the code.

Examples of coding styles you can refer to:

  • Airbnb JavaScript Style Guide

  • Google JavaScript Style Guide

Suggest automated validation code style:

  • Install eslint

  • Configure eslint with the encoding style that best suits you

  • Set a pre-submit hook to run eslint validation before submitting.

6. Summary

The more disciplined it is to write high quality and clean code, the better to overcome bad coding habits.
JavaScript is a weakly typed language with great flexibility. But you must be aware of the features you use. It is recommended that you avoid implicit type conversions and reduce the use of undefined and null.
The js language has developed very rapidly in recent years. Find the tricky code and refactor it with the latest JavaScript features.
Consistent Coding Styles in the code base facilitate readability.
Do you know any other bad coding habits in JavaScript?

Author: dmitripavlutin Translator: Front End css and js Dry Source: Dmitri Pavlutin

 

Posted by JustinMs66@hotmail.com on Mon, 06 Dec 2021 09:41:05 -0800