ตัวแปร JavaScript ไม่มีชนิด (not typed) แตค่าของมันมีชนิด ตัวแปรเดียวกันสามารถกำหนดค่าใหม่ได้ตลอดเวลา
ตัวอย่าง
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
var a;
document.write(typeof a + "\r\n");
a = true;
document.write(typeof a + "\r\n");
a = 5;
document.write(typeof a + "\r\n");
a = "web";
document.write(typeof a + "\r\n");
</script>
</body>
</html>
คำอธิบาย
typeof aคืนค่า"undefined"(เริ่มต้นไม่มีค่า)a = true→typeof a === "boolean"a = 5→typeof a === "number"a = "web"→typeof a === "string"
JavaScript เป็น Dynamically Typed
ตัวแปร (var/let/const) เป็นแค่ "ช่องเก็บ" (container) — ค่าที่เก็บไว้จึงมีชนิดข้อมูล (type) และสามารถเปลี่ยนชนิดได้ตลอดเวลา
let value = 42; // number
value = "hello"; // string
value = { key: 1 }; // object
value = () => {}; // function
นี่คือความแตกต่างจาก Statically Typed languages (C, Java, TypeScript) ที่ตัวแปรมีชนิดคงที่