Home > Web Front-end > JS Tutorial > Explain the alternative usage of && and || in javascript_Basic knowledge

Explain the alternative usage of && and || in javascript_Basic knowledge

WBOY
Release: 2016-05-16 16:41:05
Original
1265 people have browsed it

I started to study Titanium again and found that its official MVC framework (Alloy) is quite good. At first, I suffered from the lack of good code to learn and the lack of documentation, so I never studied it in detail. Later I found out that the official CodeStrong is a very good set of codes for learning. As long as you understand the entire set of codes, I believe you can basically use Alloy~

While looking at its source code, I found that usages such as the following are used in many places:

$.clouds && ($.index.add($.clouds));

I didn’t understand it very well at first. After all, this method is rarely used. After searching on Google, I realized that this method of writing is very convenient and easy to use (in fact, this method is also widely used in the source code of jquery). The following is an explanation of the alternative usage of && and || in JavaScript found online:
a() && b(): If true is returned after executing a(), b() is executed and the value of b is returned; if false is returned after executing a(), the entire expression returns the value of a(), b( ) is not executed;
a() || b(): If true is returned after executing a(), the entire expression returns the value of a(), and b() is not executed; if false is returned after executing a(), b() is executed and Return the value of b();

&& has higher priority than ||

After reading this, it is quite clear. Let’s look at the specific code:
alert((1 && 3 || 0) && 4); //Result 4 ①
alert(1 && 3 || 0 && 4); //Result 3 ②
alert(0 && 3 || 1 && 4); //Result 4 ③

Analysis:

Statement ①: 1&&3 returns 3 => 3 || 0 returns 3 => 3&&4 returns 4
Statement ②: Execute 1&&3 first to return 3, then execute 0&&4 to return 0, and finally compare the execution results with 3||0 to return 3
Statement ③: Execute 0&&3 first to return 0, then execute 1&&4 to return 4, and finally compare the execution results with 0||4 to return 4
Note: All non-zero integers are true, undefined, null and empty string "" are false.

I feel like javascript is really powerful and flexible!!

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