


An article explaining the syntax and common usage of the ternary operator in JS
This article will discuss the syntax of the ternary operator in JavaScript and some common uses. I hope it will be helpful to you!
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 null
or, 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 works
When using the ternary operator on book
, it checks if it is not null
or 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 book
is 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 book
is 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('button'); const numberElm = document.querySelector('#number'); const resultElm = document.querySelector('#result'); button.addEventListener('click', function() { resultElm.textContent = numberElm.value > 100 ? '太高' : (numberElm.value < 100 ? '太低' : '完美'); }); </script> </html>
结论
正如本教程中的示例所解释的,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!

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version
