Home > Web Front-end > JS Tutorial > body text

Analysis and examples of the difference between ternary operator and if else in JS_javascript skills

WBOY
Release: 2016-05-16 16:30:50
Original
1500 people have browsed it

Today I wrote a small demo of image carousel, using judgment

I tried if else first, the code is as follows:

Copy code The code is as follows:

if(n >= count-1){
n =0;
}else{
n ;
}

After the code is written, I am going to optimize the code and change this section to the ternary operator

Copy code The code is as follows:

n = n >= (count-1) ? n=0 : n

The results are completely different

Then I studied the difference between the two and summarized it in one sentence: ternary operation has a return value, if else has no return value

The following tests were done:

Copy code The code is as follows:

var n=1;
if(n>1){
n=0;
}else{
n ;
}
console.log(n);

Output result: 2


Ternary operation is as follows:

Copy code The code is as follows:

var n=1;
n = n>1?0 : n ;
console.log(n);
The output result is: 1

Insert a piece of other content: The difference between n and n: Simply put, n increases by 1. The difference is that n is incremented by 1 after executing the following statement; while n is done by n 1 before executing the following statement

What about n

if else statement

Copy code The code is as follows:

var n=1;
if(n>1){
n=0;
}else{
n;
}
console.log(n);
Output result: 2

Ternocular operation results

Copy code The code is as follows:

var n=1;
n = n>1?0 : n;
console.log(n); The output result is: 2


You can see the difference between if else and ternary operation~~~

There is no difference between n and n in this verification, because if else is calculated after the result, n will not be returned, and there is no return value

But for ternary operations, the n value returned by n is n itself, and the n value returned by n is the result after n 1

After reading this article, do you guys have a new understanding of the ternary operator and if else in js?

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!