1> typeof "foo"
2"string"
3> typeof true
4"boolean"
5> typeof 42
6"number"
7
8if(typeof bar === 'number') {
9 //whatever
10}
1//typeof() will return the type of value in its parameters.
2//some examples of types: undefined, NaN, number, string, object, array
3
4//example of a practical usage
5if (typeof(value) !== "undefined") {//also, make sure that the type name is a string
6 //execute code
7}
1console.log(typeof 93);
2// Output = "number"
3
4console.log(typeof 'Maximum');
5// Output = 'string'
6
7console.log(typeof false);
8// Output = "boolean"
9
10console.log(typeof anUndeclaredVariable);
11// Output = "undefined"
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
1var someValue = 'this is string';
2console.log(typeof(someValue)); // this will return string