1// get type of variable
2
3var number = 1
4var string = 'hello world'
5var dict = {a: 1, b: 2, c: 3}
6
7console.log(typeof number) // number
8console.log(typeof string) // string
9console.log(typeof dict) // object
1/"Checks if an object exists in another object's prototype chain."/
2
3function Bird(name) {
4 this.name = name;
5}
6
7let duck = new Bird("Donald");
8
9Bird.prototype.isPrototypeOf(duck);
10// returns true
1console.log(typeof "how are you?")
2"string"
3console.log(typeof false) / console.log(typeof true)
4"boolean"
5console.log(typeof 100)
6"number"
1> typeof "foo"
2"string"
3> typeof true
4"boolean"
5> typeof 42
6"number"
7
8if(typeof bar === 'number') {
9 //whatever
10}
1// Numbers
2typeof 37 === 'number';
3typeof 3.14 === 'number';
4typeof(42) === 'number';
5typeof Math.LN2 === 'number';
6typeof Infinity === 'number';
7typeof NaN === 'number'; // Despite being "Not-A-Number"
8typeof Number('1') === 'number'; // Number tries to parse things into numbers
9typeof Number('shoe') === 'number'; // including values that cannot be type coerced to a number
10
11typeof 42n === 'bigint';
12
13// Strings
14typeof '' === 'string';
15typeof 'bla' === 'string';
16typeof `template literal` === 'string';
17typeof '1' === 'string'; // note that a number within a string is still typeof string
18typeof (typeof 1) === 'string'; // typeof always returns a string
19typeof String(1) === 'string'; // String converts anything into a string, safer than toString
20
21// Booleans
22typeof true === 'boolean';
23typeof false === 'boolean';
24typeof Boolean(1) === 'boolean'; // Boolean() will convert values based on if they're truthy or falsy
25typeof !!(1) === 'boolean'; // two calls of the ! (logical NOT) operator are equivalent to Boolean()
26
27// Symbols
28typeof Symbol() === 'symbol'
29typeof Symbol('foo') === 'symbol'
30typeof Symbol.iterator === 'symbol'
31
32// Undefined
33typeof undefined === 'undefined';
34typeof declaredButUndefinedVariable === 'undefined';
35typeof undeclaredVariable === 'undefined';
36
37// Objects
38typeof {a: 1} === 'object';
39
40// use Array.isArray or Object.prototype.toString.call
41// to differentiate regular objects from arrays
42typeof [1, 2, 4] === 'object';
43
44typeof new Date() === 'object';
45typeof /regex/ === 'object'; // See Regular expressions section for historical results
46
47// The following are confusing, dangerous, and wasteful. Avoid them.
48typeof new Boolean(true) === 'object';
49typeof new Number(1) === 'object';
50typeof new String('abc') === 'object';
51
52// Functions
53typeof function() {} === 'function';
54typeof class C {} === 'function';
55typeof Math.sin === 'function';
56