Home >Web Front-end >Front-end Q&A >What are the ternary operators in JavaScript?
Javascript has only one ternary operator "? ... :", which can be used for simple selection structures. The basic syntax is "Boolean expression? sentence1 : sentence2"; when the value of "Boolean expression" is When true, sentence1 is executed, otherwise sentence2 is executed.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 5, Dell G3 computer.
javascript ternary operator
When the ternary operator in javascript is used for judgment, the basic syntax is: expression ? sentence1 : sentence2
When the value of expression
is true, execute sentence1
, otherwise execute sentence2
, Please look at the code
var b = 1, c = 1 a = 2; a >= 2 ? b++ : b--; b // 2 a < 2 ? c++ : c--; c // 0
From the above code, we will temporarily think that the ternary operator is equivalent to if else (more details below)
if(expression){ sentence1; } else { sentence2; }
When expression
is true , that is, sentence1# is executed when
expression is not
undefined,
NaN,
0,
null ##, otherwise execute
sentence2.
expression1 ? sentence1 : expression2 ? sentence2 : expression3 ? sentence3 : ...As long as the judgment of any expressionN is true, then sentenceN will be executed immediately. This judgment ends, and any subsequent judgments will no longer be executed. . And if we write the logic as if-else
if(expression1){ sentence1; } else if(expression2){ sentence2; } else if(expression3){ sentence3; } ..., it seems tiring to write the logic like this, so in the jquery and zepto source codes, we will see a lot of applications of the ternary operator.
Assignment
Another classic application scenario is assignment,var param = expression? value1 : value2, this I believe you often use
var b, c = 1; var a = b ? 2 : 1; a // 1 var a = c > 0 ? 2 : 1 a // 2
negotiate and negotiate again
One day I wrote such codefunction xx(){ var a = 1, b = 3; a < b ? return false : '' }and actually reported an error ! Why is the error reported? We will take a closer look at the multiple judgments above
expression1 ? sentence1 : expression2 ? sentence2 : expression3 ? sentence3 : ...As long as one expressionN is true, it will jump out immediately. What is the reason? We can guess that it is because the ternary operator returns sentenceN, so the judgment jumps out immediately. The usage of assignment is the same. The reason why an error is reported is that writing like
if(expression){ return (return 2); }will definitely report an error. So if we have questions about the above explanation, we can use code like this to prove: Why
var a = 1, b = 2; var c = b > 1 ? a++ : 0; c // 1c is 1, because n is added by 1 after the expression is executed. If
return a , return first and then add 1, so c here is equal to 1
Programming Video! !
The above is the detailed content of What are the ternary operators in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!