短路求值是说, 只有当第一个运算数的值无法确定逻辑运算的结果时,才对第二个运算数进行求值:当AND(&&)的第一个运算数的值为false时,其结果必定为false;当OR(||)的第一个运算数为true时,最后结果必定为true。

对于下面的test条件和isTrueisFalse方法

1
2
3
4
5
6
7
var test = true;
var isTrue = function(){
console.log('Test is true.');
};
var isFalse = function(){
console.log('Test is false.');
};

使用逻辑与 - &&.

1
2
3
4
5
6
7
8
// 普通的if语句
if(test){
isTrue(); // Test is true
}

// 上面的语句可以使用 '&&' 写为:

( test && isTrue() ); // Test is true

使用逻辑或 - ||.

1
2
3
4
5
6
test = false;
if(!test){
isFalse(); // Test is false.
}

( test || isFalse()); // Test is false.

逻辑或可以用来给参数设置默认值。

1
2
3
4
5
6
function theSameOldFoo(name){
name = name || 'Bar' ;
console.log("My best friend's name is " + name);
}
theSameOldFoo(); // My best friend's name is Bar
theSameOldFoo('Bhaskar'); // My best friend's name is Bhaskar

逻辑与可以用来避免调用undefined参数的属性时报错
例如:-

1
2
3
4
5
6
7
8
9
10
11
12
13
var dog = {
bark: function(){
console.log('Woof Woof');
}
};

// 调用 dog.bark();
dog.bark(); // Woof Woof.

// 但是当dog未定义时,dog.bark() 将会抛出"Cannot read property 'bark' of undefined." 错误
// 防止这种情况,我们可以使用 &&.

dog&&dog.bark(); // This will only call dog.bark(), if dog is defined.