Home >Web Front-end >JS Tutorial >What is the difference between the usage of ternary operator and if else in JavaScript?
I tried if else first, 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 three-eye. The way of writing the operator
n = n >= (count-1) ? n=0 : n++
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);
Output result: 2
Ternary operation 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++ 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);
Output result: 2
Ternary operation result
var n=1; n = n>1?0 : ++n; console.log(n);
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!