Hướng dẫn ternary operator javascript

The conditional [ternary] operator is the only JavaScript operator that takes three operands: a condition followed by a question mark [?], then an expression to execute if the condition is truthy followed by a colon [:], and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if...else statement.

Try it

Syntax

condition ? exprIfTrue : exprIfFalse

Parameters

condition

An expression whose value is used as a condition.

exprIfTrue

An expression which is executed if the condition evaluates to a truthy value [one which equals or can be converted to true].

exprIfFalse

An expression which is executed if the condition is falsy [that is, has a value which can be converted to false].

Description

Besides false, possible falsy expressions are: null, NaN, 0, the empty string [""], and undefined. If condition is any of these, the result of the conditional expression will be the result of executing the expression exprIfFalse.

Examples

A simple example

const age = 26;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log[beverage]; // "Beer"

Handling null values

One common usage is to handle a value that may be null:

const greeting = [person] => {
  const name = person ? person.name : "stranger";
  return `Howdy, ${name}`;
}

console.log[greeting[{ name: "Alice" }]];  // "Howdy, Alice"
console.log[greeting[null]];             // "Howdy, stranger"

Conditional chains

The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain:

function example[] {
  return condition1 ? value1
        : condition2 ? value2
        : condition3 ? value3
        : value4;
}

This is equivalent to the following if...else chain.

function example[] {
  if [condition1] {
    return value1;
  } else if [condition2] {
    return value2;
  } else if [condition3] {
    return value3;
  } else {
    return value4;
  }
}

Specifications

Specification
ECMAScript Language Specification
# sec-conditional-operator

Browser compatibility

BCD tables only load in the browser

See also

  • Cú pháp toán tử ba ngôi
  • Điều kiện nối tiếp [Conditional chains]
  • Video bài giảng
  • Luyện tập
    • Bài 1
      • Hướng dẫn
    • Bài 2
      • Hướng dẫn
  • Kết luận

Ở các bài viết trước, chúng ta đã cùng với nhau tìm hiểu hai câu lệnh điều kiện căn bản trong JavaScript là If – elseSwitch – case. Hôm nay mình sẽ giới thiệu cho các bạn một cách nữa, đó là toán tử ba ngôi [Ternary Operator] trong JavaScript.

variable_name = [condition] ? value1 : value2

Nếu condition nó là đúng [hay là true] thì toán tử sẽ trả về value 1 còn nếu là sai [hay là false] thì nó sẽ trả về giá trị của value 2

Nếu như trước đây khi phải sử dụng với if – else ta sẽ có như thế này:

var exp = 3; var salary; if [exp > 3] { salary = 1000; } else { salary = 500; } console.log[salary] // 500

Code language: JavaScript [javascript]

Thì bây giờ chỉ còn:

var exp = 1; var salary = exp > 3 ? 1000 : 500; console.log[salary] // 500 // Nếu exp có giá trị là null hoặc undefined thì sẽ gán giá trị // cho biến salary là "null or undefined"

Code language: JavaScript [javascript]

Nếu các bạn chưa hiểu rõ null và undefined là gì, hãy xem bài viết này: Phân biệt Null, Undefined và NaN.

Điều kiện nối tiếp [Conditional chains]

Toán tử điều kiện tuân theo suy dẫn phải, tức là nó có thể được gọi “nối tiếp” theo cách sau đây, tương tự như với If – else If – else If – else nối tiếp nhau:

Nếu như trước đây ta sẽ có:

var exp = 2; var salary; if [ exp < 1 ] { salary = 1000; } else if [ exp < 2 ] { salary = 1500; } else if [ exp < 3 ] { salary = 2000; } else { salary = 3000; } console.log[salary] // 2000

Code language: JavaScript [javascript]

thì bây giờ chỉ còn:

var exp = 2; var salary = exp < 1 ? 1000 : exp < 2 ? 1500 : exp < 3 ? 2000 : 3000 console.log[salary] // 2000

Code language: JavaScript [javascript]

Video bài giảng

Luyện tập

Bài 1

Viết chương trình nhập vào giá trị cho a và b. Tính tổng a và b, nếu tổng nhỏ hơn 4, hiển thị chuỗi Below, ngược lại hiển thị Over. Lưu ý sử dụng toán tử 3 ngôi.

Nếu dùng if – else:

if [[a + b] < 4] {     result = 'Below'; } else {    result = 'Over'; }

Code language: JavaScript [javascript]

Hướng dẫn

Bước 1: Tạo file add.html

Bước 2: Thêm thẻ thực hiện viết các mã JavaScript

        //code vào đây    

Code language: HTML, XML [xml]

Bước 3: Khai báo biến a, b nhập vào giá trị cho a, b từ hộp thoại

let a = prompt["a: "]; let b = prompt["b: "];

Code language: JavaScript [javascript]

Bước 4: Khai báo biến result lưu kết quả

result = [a + b < 4] ? 'Below' : 'Over';

Code language: JavaScript [javascript]

Bước 5: Thực thi chương trình. Quan sát kết quả.

Bài 2

Viết chương trình nhập vào giá trị cho chuỗi message. 

  • Nếu giá trị nhập vào là Employee thì hiển thị chuỗi Hello.
  • Còn lại nếu giá trị nhập vào là Director thì hiển thị chuỗi Greetings
  • Còn lại nếu giá trị nhập vào chuỗi rỗng thì hiển thị No login
  • Còn lại hiển thị chuỗi rỗng

Sử dụng toán tử 3 ngôi để viết chương trình.

Nếu dùng if – else:

let message; if [login == 'Employee'] {     message = 'Hello'; } else if [login == 'Director'] {     message = 'Greetings'; } else if [login == ''] {     message = 'No login'; } else {     message = ''; }

Code language: JavaScript [javascript]

Hướng dẫn

Bước 1: Tạo file employee.html

Bước 2: Thêm thẻ thực hiện viết các mã JavaScript

        //code vào đây    

Code language: HTML, XML [xml]

Bước 3: Khai báo biến message

let message = [login == 'Employee'] ? 'Hello' :     [login == 'Director'] ? 'Greetings' :       [login == ''] ? 'No login' :         '';

Code language: JavaScript [javascript]

Bước 4: Hiển thị thông báo

alert[message]

Bước 5: Thực thi chương trình. Quan sát kết quả.

Kết luận

Trong bài viết này, mình đã trình bày cách sử dụng toán tử ba ngôi, chi tiết các bạn có thể xem video để hiểu rõ hơn, các bạn để lại comment nếu có thắc mắc để được giải đáp nhé. Cảm ơn mọi người đã theo dõi bài viết!

Các bạn có thể tham khảo các bài viết hay về JavaScript tại đây.

Hãy tham gia nhóm Học lập trình để thảo luận thêm về các vấn đề cùng quan tâm.

Chủ Đề