JavaScriptThe column will introduce in detail how to correctly handle variables
Recommended ( Free): javascript (Video)
Variables are everywhere. Even if we write a small function or a gadget, we still need to declare, assign and read variables. Paying more attention to variables can improve the readability and maintainability of the code.
1. It is recommended to use const, or use let
with const
or let
Declare your own JavaScript variables. The main difference between the two is that const
variables need to be initialized when declared, and once initialized they cannot be reassigned.
// const 需要初始化 const pi = 3.14; // const 不能被重新赋值 pi = 4.89; // throws "TypeError: Assignment to constant variable"
let
The declaration does not require value initialization and can be reassigned multiple times.
// let 要不要初始化随你 let result; // let 可被重新赋值 result = 14; result = result * 2;
const
is a one-time allocation variable. Because you know that const
variables will not be modified, it is easier to speculate on const
variables than let
.
When declaring variables, const
is used first, followed by let
.
Suppose you are reviewing a function and see a const result = ...
Statement:
function myBigFunction(param1, param2) { /* 一写代码... */ const result = otherFunction(param1); /* 一些代码... */ return something; }
Although I don’t know myBigFunction()
, but we can conclude that the result
variable is read-only.
In other cases, if a variable must be reassigned multiple times during code execution, use let
.
2. Minimize the scope of variables
A variable is located in the scope in which it is created. Code blocks and function bodies create scopes for const
and let
variables.
Keeping variables in the smallest scope is a good habit to improve readability.
For example, the implementation of the following binary search 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 these variables are binarySearch()
Available within the entire scope of the function. The variable middle
is used to hold the middle index of the binary search, while the variable middleItem
holds the middle search item.
But the middle
and middleItem
variables are only used in the while
loop. So why not declare these variables directly in the while
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 within the scope where the variable is used. Their life cycles are extremely short, so it is easier to deduce their purpose.
3. Easy to use
I am always used to declaring all variables at the beginning of the function, especially when writing some larger functions. But doing this would make my intention of using the variable in the function very confusing.
So the variable should be declared as close as possible to the location where it is used. This way you don't have to guess: Oh, the variable is declared here, but... where is it used?
Suppose there is a function that contains many statements. You can declare and initialize the variable result
at the beginning of the function, but only use result
in the return
statement:
function myBigFunction(param1, param2) { const result = otherFunction(param1); let something; /* * 一些代码... */ return something + result;}
The problem isresult
Variables are declared at the beginning but only used at the end. There is no good reason to declare this variable in the first place.
So in order to better understand the function and role of result
variables, always declare the variable as close as possible to the location where it is used.
If you change the code to this:
function myBigFunction(param1, param2) { let something; /* * 一些代码... */ const result = otherFunction(param1); return something + result;}
It will be much clearer now.
4. Reasonable naming
You probably already know a lot about variable naming, so I won’t expand on it here. However, among the many naming rules, I have summarized two important principles:
The first one is very simple: use camel case naming and consistently maintain this style.
const message = 'Hello'; const isLoading = true; let count;
An exception to this rule is certain values: such as numbers or strings with special meanings. Variables that contain specific values are usually capitalized and underlined to distinguish them from regular variables:
const SECONDS_IN_MINUTE = 60; const GRAPHQL_URI = 'http://site.com/graphql';
I think the second one is: The variable name should clearly indicate what data it is used to save. .
Here are some good examples:
let message = 'Hello'; let isLoading = true; let count;
message
The name indicates that this variable contains some kind of message, most likely a string.
isLoading
is the same, it is a Boolean value used to indicate whether loading is in progress.
There is no doubt that the count
variable represents a numeric type variable that contains some counting results.
Be sure to choose a variable name that clearly indicates its role.
Look at an example, suppose you see the following code:
function salary(ws, r) { let t = 0; for (w of ws) { t += w * r; } return t; }
你能很容易知道函数的作用吗?与薪水的计算有关?非常不幸,我们很难看出 ws
、 r
、 t
、 w
这些变量名的作用。
但是如果代码是这样:
function calculateTotalSalary(weeksHours, ratePerHour) { let totalSalary = 0; for (const weekHours of weeksHours) { const weeklySalary = weekHours * ratePerHour; totalSalary += weeklySalary; } return totalSalary; }
我们就很容易知道它们的作用,这就是合理命名的力量。
5.采用中间变量
我一般尽可能避免写注释,更喜欢写出能够自我描述的代码,通过对变量、属性、函数、类等进行合理的命名来表达代码的意图。
如果想使代码本身称为文档,一个好习惯是引入中间变量,这在在处理长表达式时很好用。
比如下面的表达式:
const sum = val1 * val2 + val3 / val4;
可以通过引入两个中间变量来提高长表达式的可读性:
const multiplication = val1 * val2; const pision = val3 / val4; const sum = multiplication + pision;
再回顾一下前面的二叉搜索算法实现:
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; }
里面的 middleItem
就是一个中间变量,用于保存中间项。使用中间变量 middleItem
比直接用 array[middle]
更容易。
与缺少 middleItem
变量的函数版本进行比较:
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; }
没有中间变量的解释,这个版本稍微不太好理解。
通过使用中间变量用代码解释代码。中间变量可能会增加一些语句,但出于增强代码可读性的目的还是非常值得的的。
总结
const
,其次是 let
。The above is the detailed content of Learn to properly handle variables in JavaScript. For more information, please follow other related articles on the PHP Chinese website!