Javascript có các kiểu giá trị (không phải kiểu biến). Sau đây là các kiểu built-in sẵn có:
string
number
boolean
object
undefined
&null
symbol
(ES6)function
(ES6)
Javascript cung cấp toán tử typeof để kiểm tra kiểu giá trị:
typeof 37; // "number"
typeof 3.14; // "number"
typeof Math.LN2; // "number"
typeof Infinity; // "number"
typeof NaN; // "number"
typeof Number(1); // "number" - never use
typeof ''; // "string"
typeof 'ahihi'; // "string"
typeof '1'; // "string"
typeof (typeof 1); // "string"
typeof String('ahihi'); // "string" - never use
typeof true; // "boolean"
typeof false; // "boolean"
typeof Boolean(true); // "boolean" - never use
typeof Symbol; // "symbol"
typeof Symbold('foo'); // "symbol"
typeof Symbol.iterator; // "symbol"
typeof undefined; // "undefined"
typeof declareButUndefinedVariable; // "undefined"
typeof undeclareVariable; // "undefined"
typeof {a: 1}; // "object"
typeof [1, 2, 4]; // "object"
typeof new Date(); // "object"
// Confusing. Don't use!
typeof new Boolean(true); // "object" - never use
typeof new Number(1); // "object" - never use
typeof new String("abc"); // "object" - never use
typeof function() {}; // "function"
typeof class C {}; // "function"
typeof Math.sin; // "function"
Note: Trường hợp typeof null
là một trường hợp thú vị, vì nó sẽ trả về kiểu "object"
khi bạn mong nó sẽ trả về null
. Đây là một bug đã lâu của JS, nhưng nó giống như không bao giờ được fix - một đề xuất fix bug này về ECMAScript, nhưng nó đã bị từ chối. Nhiều code dựa trên bug này và nếu fix thì sẽ gây ra nhiều bug hơn nữa.