Console printing

typeof 'str' // 'string'
typeof NaN // 'number'
typeof 1 // 'number'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof Symbol() // 'symbol'
typeof [1,2,3] //'object'
typeof null //'object'
Copy the code

The underlying principle

Why is null, a basic data type, recognized as object by the Typeof operator? The first three bits of a binary are all zeros, and the first three bits of a null binary are all zeros, so ‘object ‘is returned when typeof is executed. —- from javascript You Don’t Know (Volume 1)

This bug is a hangover from the first version of Javascript. In this version, values are stored in 32 bytes, consisting of flag bits (1-3 bytes) and values. Flag bits store low – value data. There are five flag bits:

  • 000: object. Data is the application of the object.
  • 1: indicates a 31-bit signed integer.
  • 010: the data type is a double digit.
  • 100: string. Data is a string.
  • 110: Boolean type, data is a Boolean value.

The lowest digit is one, so the flag bit is only one byte long; Or the zero bit, the flag bit is three bytes long, two more bytes, four more types.

There are two special values:

  • Undefined (JSVAL_VOID) is -2^30 (a number outside the integer range)
  • Null (JSVAL_NULL) is a null pointer to machine code, a reference to an object type, with a value of zero.

The source code to achieve

JS_PUBLIC_API(JSType) JS_TypeOfValue(JSContext *cx, jsval v) { JSType type = JSTYPE_VOID; JSObject *obj; JSObjectOps *ops; JSClass *clasp; CHECK_REQUEST(cx); if (JSVAL_IS_VOID(v)) { // (1) type = JSTYPE_VOID; } else if (JSVAL_IS_OBJECT(v)) { // (2) obj = JSVAL_TO_OBJECT(v); if (obj && (ops = obj->map->ops, ops == &js_ObjectOps ? Cx, (clasp = OBJ_GET_CLASS (obj), clasp - > call | | clasp = = & js_FunctionClass) / / (3, 4) : ops - > call! = 0)) { // (3) type = JSTYPE_FUNCTION; } else { type = JSTYPE_OBJECT; } } else if (JSVAL_IS_NUMBER(v)) { type = JSTYPE_NUMBER; } else if (JSVAL_IS_STRING(v)) { type = JSTYPE_STRING; } else if (JSVAL_IS_BOOLEAN(v)) { type = JSTYPE_BOOLEAN; } return type; }Copy the code

2ality.com/2013/10/typ…