Skip to content

Instantly share code, notes, and snippets.

@WanderGink
Created July 16, 2017 12:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WanderGink/87312dd28b9c9da128ae22945444ef4c to your computer and use it in GitHub Desktop.
Save WanderGink/87312dd28b9c9da128ae22945444ef4c to your computer and use it in GitHub Desktop.

Javascript

Values & Types

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ị:

Number

typeof 37;                               // "number" 
typeof 3.14;                             // "number"
typeof Math.LN2;                         // "number"
typeof Infinity;                         // "number"
typeof NaN;                              // "number"
typeof Number(1);                        // "number" - never use

String

typeof '';                               // "string"
typeof 'ahihi';                          // "string"
typeof '1';                              // "string"
typeof (typeof 1);                       // "string"
typeof String('ahihi');                  // "string" - never use

Boolean

typeof true;                             // "boolean"
typeof false;                            // "boolean"
typeof Boolean(true);                    // "boolean" - never use

Symbols

typeof Symbol;                           // "symbol"
typeof Symbold('foo');                   // "symbol"
typeof Symbol.iterator;                  // "symbol"

Undefined

typeof undefined;                        // "undefined"
typeof declareButUndefinedVariable;      // "undefined"
typeof undeclareVariable;                // "undefined"

Objects

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

Functions

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment