编程知识 cdmana.com

Handling variables correctly in JavaScript

Variables are everywhere . Even if we write a small function or a small tool , Also make a statement 、 Assigning and reading variables . Increase emphasis on variables , Can improve the readability and maintainability of the code .

1. It is recommended to use const, Or use let

use const or let Declare your own JavaScript Variable . The main difference between the two is const Variables need to be initialized when they are declared , And once initialized, it cannot be reassigned .

// const  It needs to be initialized 
const pi = 3.14;
// const  Cannot be reassigned 
pi = 4.89; 
// throws "TypeError: Assignment to constant variable"

let Declaration does not need to initialize the value , It can be reassigned many times .

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

const It's a one-time allocation variable . Because you know const Variables are not modified , So with let comparison , Yes const It's easier to speculate on variables .

When declaring variables, use... First const, And then there was let .

Suppose you are review A function , And see one const result = ... Statement :

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

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

I don't know myBigFunction() What has been done in , But we can conclude that ,result Variables are read-only .

In other cases , If you have to reassign variables many times during code execution , Then use let.

2. Minimize the scope of variables

The variable is in the scope in which it was created . The code block and function body are const and let Variable creation scope .

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

For example, the following binary search algorithm implementation :

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

Variable middle and middleItem It's declared at the beginning of a function , So these variables are in binarySearch() The entire scope of a function is available . Variable middle Intermediate index used to hold binary search , Variables middleItem Save the middle search term .

however middle and middleItem Variables are only used in while In circulation . So why not just while These variables are declared in the 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 exists in the scope where variables are used . They have a very short life cycle , So it's easier to infer their use .

3. Easy to use

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

Therefore, the variable should be declared as close as possible to the location of use . So you don't have to guess : Oh , Variables are declared here , however … Where is it used ?

Let's say I have a function , There are many statements in the function . You can declare and initialize variables at the beginning of a function result, But only in return Used in the statement result

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

  /*
   *  Some codes ...
   */

  return something + result;}

The problem lies in result Variables are declared at the beginning , But only at the end . There's no good reason to declare this variable at the beginning .

So in order to better understand result The function and function of variables , Always declare the variable as close to it as possible .

If you change the code like this :

function myBigFunction(param1, param2) {
  let something;

  /* 
   *  Some codes ... 
   */

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

Is it clearer now .

4. A proper name

You probably already know a lot about variable naming , So there's no explanation here . But among the many naming rules , I've come up with two important principles :

The first one is very simple : Use the hump nomenclature , And keep that style all the time .

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

One exception to this rule is certain values : Like numbers or strings with special meanings . Variables that contain specific values are usually capitalized and underlined , Distinguish from conventional variables :

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

I think the second one is : The name of the variable should clearly indicate what data it is used to hold .

Here are some good examples :

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

message The name means that the variable contains some kind of message , It's probably a string .

isLoading It's the same thing , It's a Boolean value , Used to indicate whether loading is in progress .

without doubt ,count A variable represents a variable of numeric type , It contains some counting results .

Be sure to choose a variable name that clearly indicates its role .

Take an example , Suppose you see the following code :

function salary(ws, r) {
  let t = 0;
  for (w of ws) {
    t += w * r;
  }
  return t;
}

Can you easily know what a function does ? It's about the calculation of salary ? Very unfortunate , It's hard to see wsrtw What these variable names do .

But if the code is like this :

function calculateTotalSalary(weeksHours, ratePerHour) {
  let totalSalary = 0;
  for (const weekHours of weeksHours) {
    const weeklySalary = weekHours * ratePerHour;
    totalSalary += weeklySalary;
  }
  return totalSalary;
}

It's easy to know what they do , This is the power of proper naming .

5. Using intermediate variables

I generally try to avoid writing notes as much as possible , Prefer to write self describing code , By analyzing variables 、 attribute 、 function 、 Class and so on are named reasonably to express the intention of the code .

If you want to make the code itself a document , It's a good habit to introduce the middle variable , This works well when dealing with long expressions .

Like the following expression :

const sum = val1 * val2 + val3 / val4;

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 binary search algorithm implementation :

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;
}

Inside middleItem It's an intermediate variable , Used to save intermediate items . Use intermediate variables middleItem It's better than using it directly array[middle] More easily .

And the lack of middleItem Compare function versions of variables :

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

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

There is no explanation for the intermediate variable , This version is a little hard to understand .

By using intermediate variables Interpret code with code . Intermediate variables may add some statements , But it's worth it for the sake of code readability .

summary

  • Variables are everywhere . stay JavaScript When using variables in , The preferred const, The second is let.
  • Minimize the scope of variables . Again , Declare variables as close as possible to where they are used .
  • Proper naming is very important . Follow these rules : The name of the variable should clearly indicate what data it is used to hold . Don't be afraid to use longer variable names : Be clear, not short .
  • Last , It's better to use the code itself to interpret the code . In highly complex places , I prefer to introduce intermediate variables .

173382ede7319973.gif


This article first send WeChat messages public number : Front end pioneer

Welcome to scan the two-dimensional code to pay attention to the official account. , I push you fresh front-end technical articles every day

 Welcome to scan the two-dimensional code to pay attention to the official account. , I push you fresh front-end technical articles every day


Welcome to the rest of this column :


版权声明
本文为[Crazy technology house]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225093233815r.html

Scroll to Top