Có ba cách chuyển giá trị thành boolean. Trong 3 cách, 2 cách dùng từ khóa Boolean, cách còn lại dùng ký hiệu !!. Thảo luận chi tiết.
Dùng từ khóa Boolean
Ví dụ
Triển khai 2 cách dùng Boolean, kết quả hiển thị.
<html> <body> <script>
const isTrue = 'Golden State Warriors';
document.write(new Boolean(isTrue));
document.write("</br>");
document.write(Boolean(isTrue));
</script> </body> </html>
Kết quả
true true
Dùng !!
Ví dụ
Thay Boolean bằng ký hiệu (!!) chuyển giá trị thành Boolean.
<html> <body> <script>
const isTrue = 'Golden State Warriors';
document.write(!!isTrue);
</script> </body> </html>
Kết quả
true