ตัวดำเนินการ typeof เป็นโอเปอเรเตอร์ unary ที่วางก่อนตัวถูกดำเนินการตัวเดียว ซึ่งสามารถเป็นชนิดใดก็ได้ ค่าของมันคือสตริงที่ระบุชนิดข้อมูลของตัวถูกดำเนินการ ตัวดำเนินการ typeof จะประเมินเป็น "number", "string" หรือ "boolean" หากตัวถูกดำเนินการเป็นตัวเลข สตริง หรือค่าบูลีน และส่งคืนค่าจริงหรือเท็จตามการประเมิน
นี่คือรายการของค่าส่งคืนสำหรับ typeof โอเปอเรเตอร์
| ประเภท | ส่งคืนสตริงตามประเภท |
|---|---|
| Number | "number" |
| String | "string" |
| Boolean | "boolean" |
| object | "object" |
| ฟังก์ชัน | "ฟังก์ชัน" |
| ไม่ได้กำหนด | "undefined" |
| Null | "object" |
ตัวอย่าง
โค้ดต่อไปนี้แสดงวิธีใช้งาน typeof โอเปอเรเตอร์ -
<html>
<body>
<script>
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "Bis Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "Ais Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
</script>
</body>
</html>