Home >Web Front-end >JS Tutorial >An article explaining the syntax and common usage of the ternary operator in JS

An article explaining the syntax and common usage of the ternary operator in JS

青灯夜游
青灯夜游forward
2022-10-14 19:31:253625browse

This article will discuss the syntax of the ternary operator in JavaScript and some common uses. I hope it will be helpful to you!

An article explaining the syntax and common usage of the ternary operator in JS

The ternary operator (also known as the conditional operator) can be used to perform inline conditional checks instead of using if...else statement. It makes the code shorter and more readable. It can be used to assign a value to a variable based on a condition, or to execute an expression based on a condition.

Syntax

The ternary operator accepts three operands; it is the only operator in JavaScript that can do this. You provide a condition to test, followed by a question mark, and then two expressions separated by colons. If the condition is considered true, the first expression is executed; if it is considered false, the final expression is executed.

It is used in the following format:

condition ? expr1 : expr2

Here, condition is the condition to be tested. If its value is considered true, expr1 is executed. Otherwise, if its value is considered false, expr2 is executed.

expr1 and expr2 are any expressions. They can be variables, function calls, or even other conditions.

For example:

1 > 2 ? console.log("true") : console.log('false');

Using the ternary operator for assignment

One of the most common use cases for the ternary operator is to decide which value to assign to the variable. Often, the value of one variable may depend on the value of another variable or condition.

While this can be done using an if...else statement, it will make the code longer and less readable. For example:

const numbers = [1,2,3];
let message;
if (numbers.length > 2) {
  message = '数组太长';
} else {
  message = '数组太短';
}

console.log(message); // 数组太长

In this code example, you first define the variable message. You then use the if...else statement to determine the value of the variable.

This can be done simply in one line using the ternary operator:

const numbers = [1,2,3];
let message = numbers.length > 2 ? '数组太长' : '数组太短';

console.log(message); // 数组太长

Perform expressions using the ternary operator

Ternary operations operator can be used to execute any type of expression.

For example, if you want to decide which function to run based on the value of a variable, you can do this using the following if...else statement:

if (feedback === "yes") {
  sayThankYou();
} else {
  saySorry();
}

This can be done using The ternary operator is done in one line:

feedback === "yes" ? sayThankYou() : saySorry();

If feedback has value yes, sayThankYou will be called and the function will be executed. Otherwise, the saySorry function will be called and executed.

Using the ternary operator for null checking

In many cases you may be dealing with variables that may or may not have a defined value - for example, from the user When entering search results, or when retrieving data from the server.

Using the ternary operator, you can check whether a variable exists null by passing the variable name in place of the conditional operand. undefined

This is especially useful when the variable is an object. If you try to access a property undefined on an object that is actually nullor, an error will occur. Checking that the object is actually set first can help you avoid errors.

For example:

let book = { name: '小明', works: '斗破苍穹' };
console.log(book ? book.name : '张三'); // "小明"

book = null;
console.log(book ? book.name : '张三'); // "张三"

In the first part of this code block, book is an object with two properties - name and worksWhen using the ternary operator on book, it checks if it is not nullor undefined. If not - meaning it has a value - name then the property is accessed and will be output to the console. Otherwise, if it is empty, 张三outputs the console.

Because bookis not null, the book title will be recorded in the console. However, in the second part, when the same condition is applied, the condition in the ternary operator fails because bookis null. Therefore, "Zhang San" outputs the console.

Nested Conditions

Although the ternary operator is used inline, multiple conditions can be used as part of a ternary operator expression. You can nest or chain multiple conditions to perform condition checks similar to if...else if...else statements.

For example, the value of a variable may depend on multiple conditions. It can be done using if...else if...else:

let score = '67';
let grade;
if (score <p>In this block of code you test multiple conditions of the variable <code>score</code> to determine the variable letter grade. </p><p> These same conditions can be performed using the ternary operator, as follows: </p><pre class="brush:php;toolbar:false">let score = '67';
let grade = score <p>Evaluates the first condition, which is <code>score . If <code>true</code>, then the <code>grade</code> value is <code>F</code>. If <code>false</code>, the second expression is evaluated, which is <code>score . </code></code></p><p>This continues until all conditions are <code>false</code>, which means the value of the grade will be <code>A</code>, or until one of the conditions evaluates to <code>true</code> and its true value is assigned to <code>grade</code>. </p><h2 data-id="heading-5"><strong>示例</strong></h2><p>在这个实时示例中,您可以测试三元运算符如何在更多条件下工作。
如果您输入的值小于 100,则会显示“太低”消息。如果您输入的值大于 100,则会显示消息“太高”。如果输入 100,将显示“完美”消息。</p><pre class="brush:html;toolbar:false"><!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<style>
			#result {
				display: block;
			}

			button,
			#result {
			 margin-top: 10px;
			}
		</style>
		
	</head>
	<body>
		<div>
			<label for="number">输入一个数字</label>
			<input type="number" name="number" id="number" />
		</div>
		<button>提交</button>
		<span id="result"></span>
	</body>
	<script>
		const button = document.querySelector(&#39;button&#39;);
		const numberElm = document.querySelector(&#39;#number&#39;);
		const resultElm = document.querySelector(&#39;#result&#39;);
	
		button.addEventListener(&#39;click&#39;, function() {
			resultElm.textContent = numberElm.value > 100 ? &#39;太高&#39; : (numberElm.value < 100 ? &#39;太低&#39; : &#39;完美&#39;);
		});
	</script>
</html>

An article explaining the syntax and common usage of the ternary operator in JS

结论

正如本教程中的示例所解释的,JavaScript 中的三元运算符有很多用例。if...else在许多情况下,三元运算符可以通过替换冗长的语句来增加代码的可读性。

【相关推荐:javascript视频教程编程基础视频

The above is the detailed content of An article explaining the syntax and common usage of the ternary operator in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete