JavaScript最佳实践
鉴于公司JavaScript写的千奇百怪,整理一篇规范以便参考
Avoid global variables, avoid new, avoid ==, avoid eval()
Avoid Global Variables
Minimize the use of global variables.
This includes all data types, objects, and functions.
Global variables and functions can be overwritten by other scripts.
Use local variables instead, and learn how to use closures.
Always Declare Local Variables
All variables used in a function should be declared as local variables.
Local variables must be declared with the var, the let, or the const keyword, otherwise they will become global variables.
Strict mode does not allow undeclared variables.
Declarations on Top
It is a good coding practice to put all declarations at the top of each script or function.
This will:
Give cleaner code
Provide a single place to look for local variables
Make it easier to avoid unwanted (implied) global variables
Reduce the possibility of unwanted re-declarations
// Declare at the beginning
let firstName, lastName, price, discount, fullPrice;
// Use later
1 | firstName = "John"; |
Initialize Variables
It is a good coding practice to initialize variables when you declare them.
This will:
Give cleaner code
Provide a single place to initialize variables
Avoid undefined values
// Declare and initiate at the beginning
1 | let firstName = ""; |
Initializing variables provides an idea of the intended use (and intended data type).
Declare Objects with const
Declaring objects with const will prevent any accidental change of type:
Example
let car = {type:”Fiat”, model:”500”, color:”white”};
car = “Fiat”; // Changes object to string
const car = {type:”Fiat”, model:”500”, color:”white”};
car = “Fiat”; // Not possible
Declare Arrays with const
Declaring arrays with const will prevent any accidential change of type:
Example
let cars = [“Saab”, “Volvo”, “BMW”];
cars = 3; // Changes array to number
const cars = [“Saab”, “Volvo”, “BMW”];
cars = 3; // Not possible
Don’t Use new Object()
Use “” instead of new String()
Use 0 instead of new Number()
Use false instead of new Boolean()
Use {} instead of new Object()
Use [] instead of new Array()
Use /()/ instead of new RegExp()
Use function (){} instead of new Function()
Example
1 | let x1 = ""; // new primitive string |
Beware of Automatic Type Conversions
JavaScript is loosely typed.
A variable can contain all data types.
A variable can change its data type:
Example
1 | let x = "Hello"; // typeof x is a string |
Beware that numbers can accidentally be converted to strings or NaN (Not a Number).
When doing mathematical operations, JavaScript can convert numbers to strings:
Example
1 | let x = 5 + 7; // x.valueOf() is 12, typeof x is a number |
Subtracting a string from a string, does not generate an error but returns
NaN (Not a Number):
Example
“Hello” - “Dolly” // returns NaN
Use === Comparison
The == comparison operator always converts (to matching types) before comparison.
The === operator forces comparison of values and type:
Example
1 | 0 == ""; // true |
Use Parameter Defaults
If a function is called with a missing argument, the value of the missing argument is set to undefined.
Undefined values can break your code. It is a good habit to assign default values to arguments.
Example
1 | function myFunction(x, y) { |
ECMAScript 2015 allows default parameters in the function definition:
function (a=1, b=1) { /function code/ }
Read more about function parameters and arguments at Function Parameters
End Your Switches with Defaults
Always end your switch statements with a default. Even if you think there is no need for it.
Example
1 | switch (new Date().getDay()) { |
Avoid Number, String, and Boolean as Objects
Always treat numbers, strings, or booleans as primitive values. Not as objects.
Declaring these types as objects, slows down execution speed, and produces nasty side effects:
Example
1 | let x = "John"; |
Or even worse:
Example
1 | let x = new String("John"); |
Avoid Using eval()
The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it.
Because it allows arbitrary code to be run, it also represents a security problem.
本文作者:oldmee
本文链接:https://oldmee.github.io/2020/04/08/JavaScript-best-practices/
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。