Logical AND, OR, Ternary, Nullish Operators
Đều là xử lý “Conditional Rendering” ngắn gọn, đặc biệt là cho các UI Component dựa trên "Status" (in progress / completed, loggedin / register...)
Tenary Operator: viết ngắn gọn điều kiện IF, xử lý cả TRUE lẫn FALSE
Logical AND Operator (Short Circuit Rendering): giống IF nhưng không ELSE, chỉ xử lý TRUE, lấy giá trị sau &&
Optional Chaining: không xử lý gì cả, chỉ đơn giản là kiểm tra an toàn xem một prop có tồn tại trong object không, nếu không thì trả lại undefined
Nullish Coalescing Operator: chỉ trả lại giá trị ở bên phải khi bên trái là null hoặc undefined
Logical OR Operator: lấy giá trị TRUTHY đầu tiên
Ternary Operator
The ternary operator (?) is a concise way to write an `if` statement in JavaScript.
Ví dụ thực tế:
Logical AND Operator (Short Circuit Rendering)
Short-circuit rendering is another way to conditionally render components in React. It's based on the concept of short-circuit evaluation in JavaScript.
In short-circuit evaluation, the second operand is only evaluated if the first operand is not falsy.
Optional Chaining
Optional chaining (`?.`) is a modern operator in JavaScript that allows you to safely access nested properties of an object without having to explicitly check if each property exists.
It short-circuits the evaluation if a property is `null` or `undefined` and returns `undefined` instead of throwing an error.
Nullish Coalescing Operator
The nullish coalescing operator (`??`) is a modern operator in JavaScript that provides a way to handle default values for `null` or `undefined` values.
It's similar to the logical OR (`||`) operator, but it only returns the right-hand side operand if the left-hand side operand is `null` or `undefined`.
It doesn't return the right-hand side operand for falsy values like `0`, '' (empty string), `false`, or `NaN`.
Using Optional Chaining & Nullish Coalescing Together
Optional chaining can be used in combination with other operators like the nullish coalescing operator (`??`) to provide default values for missing properties.
Cách kết hợp này ngắn gọn hơn là IF ELSE hay Tenary Operator.
Logical OR Operator
Ứng dụng đặt giá trị mặc định
So sánh với các Operator khác:
Khi nào thì dùng cái gì trong React:
Những lỗi phổ biến
