BEST SITE FOR WEB DEVELOPERS

JS 教程

JS 首页 JS 简介 JS 去哪儿 JS 输出 JS 语句 JS 语法 JS 评论 JS 变量 JS 让 JS 常量 JS 运算符 JS 算术 JS 作业 JS 数据类型 JS 函数 JS 对象 JS 活动 JS 字符串 JS 字符串方法 JS 字符串搜索 JS 字符串模板 JS 数字 JS 数字方法 JS 数组 JS 数组方法 JS 数组排序 JS 数组迭代 JS 数组常量 JS 日期 JS 日期格式 JS 获取日期方法 JS 日期设置方法 JS 数学 JS 随机 JS 布尔值 JS 比较 JS If Else JS 开关 JS 循环 JS 循环 JS 循环 JS 循环 JS 中断 JS 可迭代对象 JS 集 JS 地图 JS Typeof JS 类型转换 JS 按位 JS 正则表达式 JS 错误 JS 作用域 JS 提升 JS 严格模式 JS this 关键字 JS 箭头函数 JS 类 JS Modules JS JSON JS 调试 JS 风格指南 JS 最佳实践 JS 错误 JS 性能 JS 保留字

JS 版本

JS 版本 JS 2009(ES5) JS 2015(ES6) 小学 2016 小学 2017 小学 2018 JS IE/Edge JS 历史

JS 对象

对象定义 对象属性 对象方法 对象显示 对象访问器 对象构造函数 对象原型 对象可迭代对象 对象集 对象映射 对象引用

JS 函数

函数定义 函数参数 函数调用 函数调用 功能应用 Function Bind 函数闭包

JS 类

课程简介 类继承 静态类

JS 异步

JS 回调 JS 异步 JS 承诺 JS 异步/等待

JS HTML DOM

DOM 简介 DOM 方法 DOM 文档 DOM 元素 DOM HTML DOM 表单 DOM CSS DOM 动画 DOM 事件 DOM 事件监听器 DOM 导航 DOM 节点 DOM 集合 DOM 节点列表

JS 浏览器 BOM

JS 窗口 JS 屏幕 JS 位置 JS 历史 JS 导航器 JS 弹出警告 JS 时机 JS Cookies

JS Web API

Web API 简介 Web 表单 API 网络历史记录 API Web 存储 API Web Worker API Web 获取 API 网络地理定位 API

JS AJAX

AJAX 简介 AJAX XMLHttp AJAX 请求 AJAX 响应 AJAX XML 文件 AJAX PHP AJAX ASP AJAX 数据库 AJAX 应用程序 AJAX 示例

JS JSON

JSON 简介 JSON 语法 JSON 与 XML JSON 数据类型 JSON 解析 JSON 字符串化 JSON 对象 JSON 数组 JSON 服务器 JSON 格式的 PHP JSON 的 HTML JSON JSONP

JS 与 jQuery

jQuery 选择器 jQuery HTML jQuery CSS jQuery DOM

JS 图形

JS 图形 JS 画布 JS Plotly JS Chart.js JS 谷歌图表 JS D3.js

JS 示例

JS 示例 JS HTML DOM JS HTML 输入 JS HTML 对象 JS HTML 事件 JS 浏览器 JS 编辑器 JS 练习 JS 测验 JS 证书

JS 参考

JavaScript 对象 HTML DOM 对象

JavaScript。W3Schools 英文版。初学者课程

尿素

JavaScript Best Practices


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 keyword or the let keyword,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
firstName = "John";
lastName = "Doe";

price = 19.90;
discount = 0.10;

fullPrice = price - discount;

This also goes for loop variables:

for (let i = 0; i < 5; i++) {

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
let firstName = "",
let lastName = "",
let price = 0,
let discount = 0,
let fullPrice = 0,
const myArray = [],
const myObject = {};

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:

例子

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:

例子

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()

例子

let x1 = "";             // new primitive string
let x2 = 0;              // new primitive number
let x3 = false;          // new primitive boolean
const x4 = {};           // new object
const x5 = [];           // new array object
const x6 = /()/;         // new regexp object
const x7 = function(){}; // new function object
亲自尝试 »

Beware of Automatic Type Conversions

JavaScript is loosely typed.

A variable can contain all data types.

A variable can change its data type:

例子

let x = "Hello";     // typeof x is a string
x = 5;               // changes typeof x to a number
亲自尝试 »

Beware that numbers can accidentally be converted to strings or NaN (Not a Number).

When doing mathematical operations, JavaScript can convert numbers to the strings:

例子

let x = 5 + 7;       // x.valueOf() is 12,  typeof x is a number
let x = 5 + "7";     // x.valueOf() is 57,  typeof x is a string
let x = "5" + 7;     // x.valueOf() is 57,  typeof x is a string
let x = 5 - 7;       // x.valueOf() is -2,  typeof x is a number
let x = 5 - "7";     // x.valueOf() is -2,  typeof x is a number
let x = "5" - 7;     // x.valueOf() is -2,  typeof x is a number
let x = 5 - "x";     // x.valueOf() is NaN, typeof x is a number
亲自尝试 »

Subtracting a string from a string, does not generate an error but returns NaN (Not a Number):

例子

"Hello" - "Dolly"    // returns NaN
亲自尝试 »

Use === Comparison

== comparison operator always converts (to matching types) before comparison.

=== operator forces comparison of values and type:

例子

0 == "";        // true
1 == "1";       // true
1 == true;      // true

0 === "";       // false
1 === "1";      // false
1 === true;     // false
亲自尝试 »

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.

例子

function myFunction(x, y) {
  if (y === undefined) {
    y = 0;
  }
}
亲自尝试 »

ECMAScript 2015 allows default parameters in the function definition:

function (a=1, b=1) { /*function code*/ }

Read more about function parameters and arguments at 函数参数


End Your Switches with Defaults

Always end your switch statements with a default. Even if you think there is no need for it.

例子

switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
    break;
  default:
    day = "Unknown";
}
亲自尝试 »

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:

例子

let x = "John";             
let y = new String("John");
(x === y) // is false because x is a string and y is an object.
亲自尝试 »

Or even worse:

例子

let x = new String("John");             
let y = new String("John");
(x == y) // is false because you cannot compare objects.
亲自尝试 »

Avoid Using eval()

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.