Home > Web Front-end > JS Tutorial > Introduction to the logical operators &&, || and ! in JavaScript_javascript skills

Introduction to the logical operators &&, || and ! in JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:23:07
Original
2235 people have browsed it

Similar to languages ​​such as C and Java, JavaScript can use three logical judgment symbols: &&, ||, and ! to make logical judgments on boolean values. Different from C and Java, the logical AND (&&) and logical OR (||) operators in JavaScript can be applied to any value, and the value returned after the operation is not necessarily a boolean value.

Processing rules for logic and &&

The processing rules of && in JavaScript are as follows:

1. Determine whether the first value is Falsy. If it is Falsy, the first value (not necessarily of boolean type) is returned directly.
2. If the first value is Truthy, return the second value directly (not necessarily of boolean type).

Copy code The code is as follows:

var o = {x:1, y:2};
console.log(o && o.y);//2
console.log(null && x);//null

Logical OR || processing rules

Similar to the && operator, the processing rules for || in JavaScript are as follows:

1. Determine whether the first value is Truthy. If it is Truthy, the first value (not necessarily of boolean type) is returned directly.
2. If the first value is Falsy, return the second value directly (not necessarily of boolean type).

This behavior of the

|| operator makes some shortcuts in JavaScript possible:

1. Get the first Truthy value from a series of values:

Copy code The code is as follows:

var a = null;
var b = 42;
var v = a || b || 100;
console.log(v);//42

2. Assign default values ​​to parameters in the function:
Copy code The code is as follows:

function test(p){
p = p || {};//if p is not passed, make it an empty object.
}

Unlike && and ||, the behavior of the ! operator is consistent with languages ​​such as C and Java, and only returns a boolean value (true or false).
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template