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

What is the difference between the usage of ternary operator and if else in JavaScript?

伊谢尔伦
Release: 2017-07-19 09:24:46
Original
1519 people have browsed it

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

if(n >= count-1){
n =0;
}else{
n ++;
}
Copy after login

After the code is written, I am going to optimize the code and change this section to three-eye. The way of writing the operator

n = n >= (count-1) ? n=0 : n++
Copy after login

The result is completely different

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

Did the following test:

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

Output result: 2

Ternary operation is as follows:

var n=1;
n = n>1?0 : n++;
console.log(n);
Copy after login

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++ only adds 1 after executing the following statements; while ++n does n+1 first before executing the following statements

So what about ++n

if else statement

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

Output result: 2

Ternary operation result

var n=1;
n = n>1?0 : ++n; 
console.log(n);
Copy after login

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 It is after the calculation 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.

The above is the detailed content of What is the difference between the usage of ternary operator and if else in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

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!