Sử dụng toán tử typeof để kiểm tra kiểu dữ liệu.
Ví dụ
<!DOCTYPE html>
<html>
<body>
<script>
var answer = true;
if (typeof answer === "boolean") {
alert("Là Boolean");
} else {
alert("Không phải Boolean");
}
// Test các giá trị khác
console.log(typeof true); // "boolean"
console.log(typeof false); // "boolean"
console.log(typeof Boolean(1)); // "boolean"
console.log(typeof new Boolean(true)); // "object" !!
console.log(typeof "true"); // "string"
console.log(typeof 1); // "number"
</script>
</body>
</html>
Lưu ý quan trọng:
| Giá trị | typeof | Là boolean primitive? |
|---|---|---|
true / false | "boolean" | ✅ Có |
Boolean(expr) | "boolean" | ✅ Có |
new Boolean(true) | "object" | ❌ Không (là object) |
"true" | "string" | ❌ Không |
1 / 0 | "number" | ❌ Không |
Hàm kiểm tra an toàn (bao gồm cả Boolean object):
function isBoolean(val) {
return typeof val === 'boolean' || val instanceof Boolean;
}
isBoolean(true); // true
isBoolean(false); // true
isBoolean(new Boolean(true)); // true
isBoolean("true"); // false
Khuyến nghị: Chỉ dùng primitive boolean (true/false), tránh new Boolean().