Analysis and example of the difference between the ternary operator and if else in JS

  • 2020-03-30 04:20:32
  • OfStack

Today, I wrote a small demo of picture rotation, using the judgment

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


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

After the code is written, we are ready to optimize the code and change this to a ternary operator
 

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

The results are completely different

We then looked at the difference and concluded it in one sentence: the ternary operation has a return value, if or else has no return value

The following tests were conducted:
 


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

Three unary As follows:
 


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

The difference between ++n and n++ : in short, both are n+ 1. The difference is that n++ is added to the end of the statement; So plus plus n is going to do n plus 1 before we do anything else

What about plus plus n

If the else statement


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

The result of a trinomial operation
 


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 operations
 
N ++ and ++n don't make any difference in this validation, because if or else is after the computation, it doesn't return n, it doesn't return any value
 
But for a ternary operation, n++ returns n itself, and ++n returns n after n+1

After reading this article, you may have a new understanding of the ternary operator and if else in js.


Related articles: