How to Handle Variables Correctly in JavaScript

  • 2021-10-15 09:47:29
  • OfStack

Variables are everywhere. Even if we write a small function or a gadget, we should declare, assign values and read variables. Increasing the emphasis on variables can improve the readability and maintainability of code.

1. const is recommended, or let is recommended

Declare your own JavaScript variable with const or let. The main difference between the two is that the const variable needs to be initialized at declaration time, and once initialized, it cannot be re-assigned.


// const  Need to initialize 
const pi = 3.14;
// const  Cannot be reassigned 
pi = 4.89; 
// throws "TypeError: Assignment to constant variable"

The let declaration does not need to initialize the value and can be re-assigned multiple times.


// let  It's up to you whether you want to initialize it or not 
let result;
// let  Can be reassigned 
result = 14;
result = result * 2;

const is a quadratic allocation variable. Because you know that the const variable will not be modified, it is easier to guess the const variable than let.

const is preferred when declaring variables, followed by let.

Suppose you are working on an review 1 function and see an const result =... declaring:


function myBigFunction(param1, param2) {
 /* 1 Write code ... */

 const result = otherFunction(param1);
 /* 1 Some codes ... */
 return something;
}

Although we don't know what is done in myBigFunction (), we can conclude that the result variable is read-only.

In other cases, use let if you have to reassign variables several times during code execution.

2. Minimize the scope of a variable

Variable is in the scope in which it was created. Code blocks and function bodies create scopes for const and let variables.

Keeping variables in the minimum scope is a good habit to improve readability.

For example, the implementation of the following 2-point lookup algorithm:


function binarySearch(array, search) {
 let middle; let middleItem; let left = 0;
 let right = array.length - 1;

 while(left <= right) {
  middle = Math.floor((left + right) / 2);  
  middleItem = array[middle];  
  if (middleItem === search) { 
   return true; 
  }
  if (middleItem < search) { 
   left = middle + 1; 
  } else {
   right = middle - 1; 
  }
 }
 return false;
}

binarySearch([2, 5, 7, 9], 7); // => true
binarySearch([2, 5, 7, 9], 1); // => false

The variables middle and middleItem are declared at the beginning of the function, so they are available throughout the scope of the binarySearch () function. The variable middle is used to hold the intermediate index of the 2-fork search, while the variable middleItem holds the intermediate search term.

However, the middle and middleItem variables are only used in the while loop. Then why not declare these variables directly in the while code block?


function binarySearch(array, search) {
 let left = 0;
 let right = array.length - 1;

 while(left <= right) {
  const middle = Math.floor((left + right) / 2);  
   const middleItem = array[middle];  
   if (middleItem === search) {
    return true; 
  }
  if (middleItem < search) {
   left = middle + 1; 
  } else {
   right = middle - 1; 
  }
 }
 return false;
}

Now middle and middleItem only exist in the scope where variables are used. Their life cycle is extremely short, so it is easier to infer their use.

3. Easy to use

I am used to declaring all variables at the beginning of a function, especially when writing a larger function. But doing so makes my intention to use variables in functions very confusing.

Therefore, the position should be used as close as possible when declaring variables. So you don't have to guess: Oh, variables are declared here, but … where is it used?

Suppose there is a function, and the function contains many statements. You can declare and initialize the variable result at the beginning of the function, but only result is used in the return statement:


function myBigFunction(param1, param2) {
 const result = otherFunction(param1); 
 let something;

 /*
  * 1 Some codes ...
  */

 return something + result;}

The problem is that the result variable is declared at the beginning, but only used at the end. There is no good reason to declare this variable after the beginning.

Therefore, to better understand the function and function of result variables, always make the variable declaration as close as possible to where it is used.

If you change the code to this:


function myBigFunction(param1, param2) {
 let something;

 /* 
  * 1 Some codes ... 
  */

 const result = otherFunction(param1); 
 return something + result;}

Is it much clearer now?

4. Reasonable naming

You probably already know a lot about variable naming, so you won't expand on it here. However, among the numerous naming rules, I have summed up two important principles:

The first one is very simple: use hump nomenclature and keep this style as 1.


const message = 'Hello';
const isLoading = true;
let count;

One exception to this rule is a specific value, such as a number or a string with a special meaning. Variables that package specific values are usually in the form of uppercase and underlined, which is distinguished from regular variables:


const SECONDS_IN_MINUTE = 60;
const GRAPHQL_URI = 'http://site.com/graphql';

I think Rule 2 is: Variable names should clearly indicate what data is used to hold.

Here are some good examples:


let message = 'Hello';
let isLoading = true;
let count;

The message name indicates that this variable contains some kind of message, most likely a string.

isLoading is a Boolean value indicating whether a load is in progress.

There is no doubt that the count variable represents a variable of numeric type, which contains 1 count result.

1 Be sure to choose a variable name that can clearly indicate its function.

Look at an example, suppose you see the following code:


// let  It's up to you whether you want to initialize it or not 
let result;
// let  Can be reassigned 
result = 14;
result = result * 2;
0

Can you easily know the function? Is it related to the calculation of salary? Unfortunately, it's hard to see what the variable names ws, r, t, w do.

But if the code is like this:


// let  It's up to you whether you want to initialize it or not 
let result;
// let  Can be reassigned 
result = 14;
result = result * 2;
1

We can easily know their function, which is the power of reasonable naming.

5. Use intermediate variables

I generally avoid writing comments as much as possible, preferring to write code that can describe itself, and express the intention of the code by naming variables, attributes, functions, classes, etc. reasonably.

If you want to make the code itself a document, a good habit is to introduce intermediate variables, which are useful when dealing with long expressions.

For example, the following expression:


// let  It's up to you whether you want to initialize it or not 
let result;
// let  Can be reassigned 
result = 14;
result = result * 2;
2

You can improve the readability of long expressions by introducing two intermediate variables:


const multiplication = val1 * val2;
const division    = val3 / val4;

const sum = multiplication + division;

Review the previous 2-fork search algorithm implementation under 1:


// let  It's up to you whether you want to initialize it or not 
let result;
// let  Can be reassigned 
result = 14;
result = result * 2;
4

middleItem inside is an intermediate variable, which is used to hold intermediate items. It is easier to use the intermediate variable middleItem than to use array [middle] directly.

Compare with the version of the function that lacks the middleItem variable:


// let  It's up to you whether you want to initialize it or not 
let result;
// let  Can be reassigned 
result = 14;
result = result * 2;
5

Without the explanation of intermediate variables, this version is slightly less understandable.

Interpret code with code by using intermediate variables. The intermediate variable may add 1 statement, but it is worth it for the purpose of enhancing the readability of the code.

Summarize

Variables are everywhere. When using variables in JavaScript, const is preferred, followed by let. Minimize the scope of variables as much as possible. Similarly, declare variables as close to where they are used as possible. Reasonable naming is very important. Follow the following rules: Variable names should clearly indicate what data is used to hold. Don't be afraid to use longer variable names: pursue clarity rather than brevity. Finally, it is best to interpret the code by itself. In highly complex places, I prefer to introduce intermediate variables.

The above is how to correctly handle variables in JavaScript in detail, more information about JavaScript handling variables please pay attention to other related articles on this site!


Related articles: