Do not Baidu and write code to test.
The first question, what is the output of the following two lines of code?
console.log(1<2 && 4>5)
console.log(1<2 || 4>5)
The second question, what is the output of the following two lines of code?
console.log(2 && 4)
console.log(2 || 4)
If you are not clear about these questions, it means you are not clear about the operation process of && and ||.
What is their operation process?
Take a look at the following image.
For example, console.log(2 && 4)
both 2 and 4 are true.
console.log( 2 && 4 )
true && true
The result returned is the data of the last judgment. 4 is the last one to be judged, so the result returned is 4.
Verify it.
How to calculate console.log(2 || 4)
?
Also, do the judgment first. 2 is true, and the || operation only needs one to be true, so there is no need to judge the 4 afterwards.
Because the result returned is the data of the last judgment, the result returned is 2.
Verify it.
So how do we use it in actual development?
For example, we have an object here.
var obj = {}
Assume it comes from somewhere else, and you don't know what properties are in this object.
Now we want to read a property 'a' from this object.
My requirement is to read 'a' if it has a value, and if it doesn't have a value, give it a default value.
In normal writing, it would be written like this:
var a = obj.a
if(!a) {
a='default'
}
Using ||, you only need
var a = obj.a || 'default'
The code is much simpler.
According to the judgment process, if obj.a has a value, the return is true, and the result returned is the data of the last judgment, so a = obj.a.
If obj.a does not have a value, it will continue to judge the following, 'default' returns true, so a = 'default'.
For example, we want to know if there is a function in obj, and if so, call it.
The conventional way is
if(obj.func) {
obj.func()
}
Using &&, it is
obj.func && obj.func()
Everyone can think about this themselves.