1024programmer JavaScript 5 bad habits of JS coding, how to avoid them?

5 bad habits of JS coding, how to avoid them?

Have you ever had this feeling when reading Javascript code

  • You hardly understand the code role?

  • The code uses a lot of Javascript tricks?

  • Naming and coding style too arbitrary?

  • These are all symptoms of bad coding habits.

In this article, I describe 5 common bad coding habits in Javascript. Importantly, this article will give some actionable suggestions on how to get rid of these habits.

1. Do not use implicit type conversion

Javascript is a A loosely typed language. When used correctly, this is a benefit because it gives you flexibility.

Most operators + – * / == (excluding ===) perform implicit conversions when dealing with operands of different types.

The statements if(condition) {…}, while(condition){…} implicitly convert the condition to a Boolean value.

The following example relies on implicit conversion of types, which can sometimes be confusing:

console.log  ("2" + "1"); // => "21"
 console.log("2" - "1"); // => 1
 console.log('' == 0); // => true
 console.log(true == []); // -> false
 console.log(true == ![]); // -> false

Relying too much on implicit type conversions is a bad habit. First, it makes your code less stable in edge cases. Second, there is an increased chance of introducing bugs that are difficult to reproduce and fix.

Now we implement a function to get the properties of the 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() Read the value of the name attribute, which is ‘Batman’.

Then try to access the isVillian property:

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

This is an error. Even though the property isVillian of hero is false, the function getProp() returns false true.

This is because the validation of the property’s existence relies on the boolean value being implicitly converted by if(!object[propertyName]){…}.

These errors are hard to find, to fix this function, it is necessary to explicitly validate the type of the value:

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 Exactly verifies if the property is undefined.

It is recommended to avoid using undefined directly. Therefore, the above solution can be further improved:

function getPropFixedBetter(object, propertyName, defaultValue) {
   if (!(propertyName in object)) {
     return defaultValue;
   }
   return object[propertyName]
 }

Forgive the author’s suggestion: Do not use implicit type conversion as much as possible. Instead, make sure variables and function parameters always have the same type, using explicit type conversions when necessary.

Best practice list:

  • Always use the strict equality operator === for comparisons

  • Do not use the loose equality operator ==

  • Addition operator operand1 + operand2: both operands should be numbers or string

  • Arithmetic operators – */%**: Both operands should be numbers

  • if (condition) {…}, while (condition) {…} and other statements: condition must be a Boolean value

  • You may say that this method requires Write more code…you’re right! But with explicit methods, you can control the behavior of your code. Additionally, explicitness improves readability.

2. Don’t use early Javascript tricks

The interesting thing about Javascript is that its creators didn’t expect the language to become so popular.

The complexity of applications built on Javascript is growing faster than the language. This situation forces developers to use Javascript tricks and workarounds just to make things work.

A typical example is to check whether an array contains a certain element. I never liked using array.indexOf(item)! == -1 to check.

ES6 and beyond are much more powerful, and many tricks can be safely refactored to use new language features.

ES6 can use array.includes(item) instead of array.indexOf(item) !== -1

3. Don’t pollute the function scope

Before ES2015, you may develop the habit of declaring all variables in the function scope.

Look at 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 in function scope. But these variables affect the function scope, because they are only needed within the scope of the for() block.

By introducing let and const with block scope, the lifetime of variables should be limited as much as possible.

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 are restricted to for() loop block scope. length is moved to the vicinity of where it is used.

The refactored code is easier to understand, because variables are not scattered throughout the scope of the function, they exist near where they are used.

Define variables at block scope where used

if block scope

// not good
 let message;
 //...
 if (notFound) {
   message = & # 39; Item not found & # 39;;
   // Use `message`
 }
 // good
 if (notFound) {
   const message = & # 39; Item not found & # 39;;
   // Use `message`
 }
 for block scope
 // not good
 let item;
 for (item of array) {
   // Use `item`
 }
 // good
 for (const item of array) {
   // Use `item`
 }

4. Try to avoid undefined and null

Unassigned variables By default it is assigned the value undefined. For example

let count;
 console.log(count); // => undefined
 const hero = {
   name: 'Batman'
 };
 console.log(hero.city); // => undefined

The count variable is defined but not yet initialized with a value. Javascript implicitly assigns it undefined.

When accessing the non-existing attribute hero.city, undefined will also be returned.

Why is it a bad habit to use undefined directly? Because when comparing to undefined you are dealing with variables in an uninitialized state.

Variables, object properties, and arrays must be initialized with values ​​before use

JS provides many ways to avoid comparisons with undefined.

Judge whether the attribute exists

// not good
 const object = {
   prop: 'value'
 };
 if (object.nOnExistingProp=== undefined) {
   //...
 }
 // good
 const object = {
   prop: 'value'
 };
 if ('nonExistingProp' in object) {
   //...
 }

The default property of the object

// not good
 function foo(options) {
   if (object. optionalProp1 === undefined) {
     object.optionalProp1 = & # 39; Default value 1 & # 39;;
   }
   //...
 }
 // good
 function foo(options) {
   const defaultProps = {
     optionalProp1: & # 39; Default value 1 & # 39;
   };
   optiOns = {
     ...defaultProps,
     ...options
   }
 }

Default function parameters

// not good
 function foo(param1, param2) {
   if (param2 === undefined) {
     param2 = & # 39; Some default value & # 39;;
   }
   //...
 }
 // good
 function foo(param1, param2 = 'Some default value') {
   //...
 }

null is an indicator of a missing object. Returning null from functions should be avoided as much as possible, especially when functions are called with null as an argument.

Once a null appears on the call stack, its presence must be checked in every function that might access it, which is error-prone.

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 doesn’t involve null. An alternative is the try/catch mechanism, which defaults to the use of objects.

5. Do not use random coding style, implement a standard

What’s more intimidating than reading code with random coding styles? You never know what to expect!

What if the code base contains the different coding styles of many developers?

The entire team and application codebase requires the same coding style, which improves code readability.

Some examples of useful coding style:

Airbnb JS Style Guide

Google JS Style Guide

Honestly, when I I might forget to style my code when I get home and get ready to commit.

I always say to myself: keep the code the same and update it later, but “later” means never.

It is recommended to use eslint to standardize the coding style.

Install eslint

Configure eslint with the coding style that suits you best

Set up a pre-submit hook to run eslint before submitting verify.

Summary

Writing high quality and clean code requires discipline and overcoming bad coding habits.

Javascript is a forgiving language with great flexibility. But you have to be careful which features you use. The advice here is to avoid implicit type conversions, undefined and null .

The language is developing quite fast now. Find complex code and refactor it to use the latest JS features.

A consistent coding style across the entire codebase benefits readability. Good programming skills are always a win-win solution.

Recommended tutorial: “JS Tutorial”

The above are 5 bad habits of JS coding, how to avoid them? For more details, please pay attention to other related articles on 1024programmer.com!

Law, to overcome bad coding habits.

Javascript is a forgiving language with great flexibility. But you have to be careful which features you use. The advice here is to avoid implicit type conversions, undefined and null .

The language is developing quite fast now. Find complex code and refactor it to use the latest JS features.

A consistent coding style across the entire codebase benefits readability. Good programming skills are always a win-win solution.

Recommended tutorial: “JS Tutorial”

The above are 5 bad habits of JS coding, how to avoid them? For more details, please pay attention to other related articles on 1024programmer.com!

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/5-bad-habits-of-js-coding-how-to-avoid-them/

author: admin

Previous article
Next article

Leave a Reply

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

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索