Table of Contents
Syntax
Using the ternary operator for assignment
Perform expressions using the ternary operator
Using the ternary operator for null checking
Nested Conditions
示例
结论
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

Oct 14, 2022 pm 07:31 PM
javascript ternary operator

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
Copy after login

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');
Copy after login

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); // 数组太长
Copy after login

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); // 数组太长
Copy after login

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();
}
Copy after login

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

feedback === "yes" ? sayThankYou() : saySorry();
Copy after login

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 : '张三'); // "张三"
Copy after login

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 id="strong-示例-strong"><strong>示例</strong></h2><p>在这个实时示例中,您可以测试三元运算符如何在更多条件下工作。
如果您输入的值小于 100,则会显示“太低”消息。如果您输入的值大于 100,则会显示消息“太高”。如果输入 100,将显示“完美”消息。</p><pre class='brush:php;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>
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles