Conditional operators if, '?'

Javascript Conditional Operators: if, ‘?’

There are five conditional statements in JavaScript:

  • We use else if to identify a new condition to test, if the first condition is false; else if to identify a block of code to be executed, if a specified condition is true; else to identify a block of code to be executed, if the same condition is false;

  • We use ‘?’ as shorthand for an if…else statement. (-我们使用“?”作为if… else语句的简写。)

  • We use switch to identify a lot of alternative blocks of code to be executed. (-我们使用switch来识别许多要执行的替代代码块。)

The “if” Statement

The “if” Statement (“if”语句)

The if(…) statement is the most fundamental of the conditional statements, as it evaluates whether a statement is true or false, and runs only if the statement returns true. In case of a false result the code block will be ignored and the program will skip to the next section. (If (…)语句是条件语句中最基本的语句,因为它评估语句是TRUE还是FALSE ,并且仅在语句返回TRUE时运行。如果出现错误结果,代码块将被忽略,程序将跳到下一节。)

Syntax:

Syntax:

if (condition) {
 //if the condition is true block of code  executed 
}

We use if in lowercase letters because uppercase letters (If or IF) will generate a JavaScript error. (>我们使用小写字母if ,因为大写字母( If或IF )会生成JavaScript错误。)

The condition in this example is a simple equality check (answer == ‘yes’), but it can be much more complicated. (此示例中的条件是一个简单的相等性检查( answer = = ‘yes’ ) ,但它可能要复杂得多。)

let answer = prompt('Do you like w3cdoc?', '');
if (answer == 'yes') {
 console.log('Thanks!');
}

When we execute more than one statement, we must write our code block inside curly brackets. (当我们执行多个语句时,我们必须将代码块写在大括号中。)

Syntax:

Syntax:

if (condition) {
 statement1;
 statement2;
}

Example of the if(…) with code block inside curly brackets:

if (true) {
 let message = 'Welcome to w3cdoc!'
(let message = '欢迎使用w3cdoc !')
 console.log(message);
}

We recommend you to write your code between curly braces {} every time you use an if statement, no matter that there is only one statement to execute, as it improves readability.

Nested if statement means an if statement inside that statement. JavaScript allows us to nest if statements within if statements. For example, we can place an if statement inside another if statement. (嵌套if语句表示该语句内的if语句。JavaScript允许我们在if语句中嵌套if语句。例如,我们可以在另一个if语句中放置if语句。)

Syntax:

Syntax:

if (condition1) {
 //When condition1 is true it's executes 
(//当condition1为true时,它会执行)
 if (condition2) {
   //When condition2 is true it's executes 
(//当condition2为true时,它执行)
 }
}

Boolean Conversion

Boolean Conversion (布尔转换)

The if(…) statement evaluates the expression in the parentheses converting the result to a boolean. (If (…)语句计算括号中的表达式,将结果转换为布尔值。)

Let’s remember the conversion rules from the chapter Data Types:

  • An empty string “”, a number 0, null, undefined, and NaN become false. That’s the reason why they are called “falsy” values. (-空字符串“”、数字0、null、undefined和NaN变为false。这就是为什么它们被称为“虚假”价值观的原因。)

  • Other values become true and they are called “truthy”. (-其他价值观变为真实,它们被称为“真实”。)

So this code would never execute:

if (0) { // 0 is falsy
 ...
}

This one will:

if (1) { // 1 is truthy
 ...
}
if (1) {
console.log('Welcome to w3cdoc!');
}

The “else” Statement

The “else” Statement (“else”声明)

The if(…) statement can contain an optional else block, which executes when the condition is false. (If (…)语句可以包含一个可选的else块,该块在条件为false时执行。)

The else statement should be written after the if statement, and has no condition in parentheses. Here is the syntax for a simple if…else statement. (Else语句应写在if语句之后,括号中没有条件。下面是一个简单的if… else语句的语法。)

if (condition) {
 //this code  will execute if the condition is true
} else {
 // this code  will execute if the condition is false
}

Example of the “else” statement:

let i = 16;
if (i != 16 ) {
 console.log("it’s not i");
} else {
 console.log("it’s i");
}

The “else if” Statement

The “else if” Statement (“else if”语句)

The else if statement let us to test several variants of a condition, when we need more than two options. In other words, we use the else if statement to specify a new condition if the first one is false. (Else if语句允许我们在需要两个以上选项时测试条件的几个变体。换句话说,如果第一个条件为false ,则使用else if语句指定新条件。)

Syntax:

Syntax:

if (condition) {
 statement;
} else if (condition) {
 statement;
 .
(图/)指传媒截图)
 .
} else {
 statement;
}

Example of the else if statement:

let number = prompt('Guess the secret number?', '');
if (number > 16) {
 console.log("The number is smaller!");
} else if (number < 16) {
 console.log("The number is greater!");
} else {
 console.log("You guessed!")
}

In the example above, JavaScript first checks number > 16. If it is falsy, it goes to the next condition number < 16. If it is falsy as well, it will show the last alert. There can be more else if blocks, the last and final else is optional.

JavaScript will try to run all the statements in order, and will default to the else block if none of them are successful. In case of many else ifstatements, the switch statement can be preferred for readability. (JavaScript将尝试按顺序运行所有语句,如果没有成功,则默认为else块。在许多其他ifstatements的情况下,为了可读性, switch语句可能是首选。)

Conditional operator ‘?’

Conditional operator ‘?’ (条件运算符“?”)

The “conditional” or “question mark” operator lets us in a shorter and simpler way assign a variable. The operator is also called “ternary”, because it has three operands. It is actually the only JavaScript operator which has that many. Conditional (ternary) statements are an integral part of all programming languages, which used to perform different actions based on different conditions. For doing that you can use the if statement and the conditional operator ‘?’ (“question mark”) in your code.

Example of the conditional operator:

let booleanValue;
let number = prompt('Guess the secret number?', '');
if (number != 18 ) {
 booleanValue = false;
} else {
 booleanValue = true;
}
console.log(booleanValue);

Syntax:

Syntax:

let result = condition ? value1 : value2;

If the condition is true, the operator returns the value of value1; otherwise, it returns the value of value2.

Condition: An expression which evaluates to true or false.

Example of the condition:

let booleanValue = (number != 18) ? false : true;

The example executes the same thing as the previous one, but parentheses make the code more readable, so we recommend using them. (示例执行的内容与上一个相同,但括号使代码更具可读性,因此我们建议使用它们。)

// the comparison operator "number != 18" executes first anyway
// (no need to wrap it into parentheses)
let booleanValue = number != 18  ? false : true;

You can avoid using the question mark operator in the example above, because the comparison itself returns true/false:

// the same
let booleanValue = number > 18;

Multiple ‘?’

Multiple ‘?’ (多个)

An arrangement of question mark operators ? can return a value that depends on more than one condition. (问号运算符的排列?可以返回依赖于多个条件的值。)

let number = prompt('number?', '');
let message = (number < 16) ? "The number is smaller!":
(number > 16)  ? "The number is greater!" :"You guessed!"
console.log( message );

It can seems difficult for you to understand, but after a closer look, you can see that it’s just a standard sequence of tests:

  • The first ? checks if number < 16.

  • In case it is true – it returns “The number is smaller!”. If not, it continues to the expression after the colon “:”, checking number > 16.

  • If that’s true – it returns"The number is greater!" . If not, it continues to the expression after the next colon “:”.

  • And returning ‘You guessed!’. (-并返回“你猜对了!”。)

Non-traditional use of ‘?’

Non-traditional use of ‘?’ (“?”的非传统用法)

Sometimes we use the question mark ? as a replacement for if:

let number = prompt('Write the number', '');
(number == 16) ? console.log("it’s right number") : console.log("it’s wrong number");

Either the first or the second expression after the question mark gets executed showing an alert, what depends on the condition number == 16. (显示警报的问号执行后的第一个或第二个表达式,取决于条件编号= = 16。)

In this case we don’t assign a result to a variable, but execute different code depending on the condition. Note, that it’s not recommended to use the question mark operator in this way. (在这种情况下,我们不将结果分配给变量,而是根据条件执行不同的代码。请注意,不建议以这种方式使用问号运算符。)

The reason is the notation, which is shorter than the equivalent if statement, that appeals to some programmers. (原因是这个符号比等效的if语句短,吸引了一些程序员。)

Let’s look at the same code using if for comparison:

let number = prompt('Write the number', '');
if (number == 16) {
 console.log("it’s a right number")
} else {
 console.log("it’s a wrong number");
}

Here the code is located vertically. It’s easier to understand the code blocks which span several lines than a long, horizontal instruction set. (此处代码垂直放置。与长而水平的指令集相比,跨越几行的代码块更容易理解。)

The main purpose of the question mark operator is to return one value or another, it depends on its condition. So use it for exactly that, when you need to execute different branches of code. (问号运算符的主要目的是返回一个值或另一个值,这取决于其条件。因此,当您需要执行不同的代码分支时,请使用它。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部