## 意外使用赋值运算符

avaScript程序可能如果程序员不小心使用赋值运算符（=）产生意想不到的结果，而不是一个比较运算符（==）在一个if语句.

if语句返回false（如预期），因为x不等于10:

```var x = 0;
if (x == 10)
```

if语句返回true（可能不如预期），因为10是true:

```var x = 0;
if (x = 10)
```

```var x = 0;
if (x = 0)
```

## 期待宽松的比较

```var x = 10;
var y = "10";
if (x == y)
```

```var x = 10;
var y = "10";
if (x === y)
```

```var x = 10;
switch(x) {
}
```

```var x = 10;
switch(x) {
}
```

## 混淆加和连接

```var x = 10 + 5;          // the result in x is 15
var x = 10 + "5";        // the result in x is "105"
```

```var x = 10;
var y = 5;
var z = x + y;           // the result in z is 15

var x = 10;
var y = "5";
var z = x + y;           // the result in z is "105"
```

## 误解浮点类型

```var x = 0.1;
var y = 0.2;
var z = x + y            // the result in z will not be 0.3
```

```var z = (x * 10 + y * 10) / 10;       // z will be 0.3
```

## 换行JavaScript字符串

JavaScript允许在两行声明语句:

```var x =
"Hello World!";
```

```var x = "Hello
World!";
```

```var x = "Hello \
World!";
```

## 错位的分号

```if (x == 19);
{
// code block
}
```

## 换行Return语句

```function myFunction(a) {
var power = 10
return a * power
}
```

```function myFunction(a) {
var power = 10;
return a * power;
}
```

JavaScript 允许将一个语句写在两行.

```function myFunction(a) {
var
power = 10;
return a * power;
}
```

```function myFunction(a) {
var
power = 10;
return
a * power;
}
```

```function myFunction(a) {
var
power = 10;
return;
a * power;
}
```

## 解释

```var
```

JavaScript将尝试通过阅读下一行完整的声明:

```power = 10;
```

```return
```

JavaScript会自动关闭它，像这样:

```return;
```

JavaScript将关闭在行末的return语句，因为它是一个完整的语句。

## 使用命名索引访问数组

JavaScript不支持数组命名索引.

```var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length;         // person.length will return 3
var y = person[0];             // person[0] will return "John"
```

```var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length;         // person.length will return 0
var y = person[0];             // person[0] will return undefined
```

## 用逗号结束数组定义

```points = [40, 100, 1, 5, 25, 10,];
```

Some JSON and JavaScript engines will fail, or behave unexpectedly.

```points = [40, 100, 1, 5, 25, 10];
```

## 用逗号结束对象定义

```person = {firstName:"John", lastName:"Doe", age:46,}
```

```person = {firstName:"John", lastName:"Doe", age:46}
```

## 未定义不是空

JavaScript中, null 针对对象, undefined 用于变量、属性和方法。

```if (myObj !== null && typeof myObj !== "undefined")
```

```if (typeof myObj !== "undefined" && myObj !== null)
```

## 异常块的作用域

JavaScript 不为每个代码块创建新的作用域

```for (var i = 0; i < 10; i++) {
// some code
}
return i;
```