The following sample code shows the typeof operator in use:
const str = 'Im a string'; console.log(typeof str); // Expected output: string
In the example above, const str is a String and serves as the operand for the typeof operator.
The expected output of the typeof operator, when applied to a String, is “string”.
JavaScript variables have different data types, and each data type has a different set of properties and methods.
Furthermore, these data types may interact with one another. When they do so, the results of the interactions are type-dependent. For example, when adding a String to a Number the result will be a concatenation of the two values as if they were both strings, as seen below:
const str = 'Im a string'; const num = 3; console.log(num + str); // Expected output: 3Im a string
In the example above, const str is a String, and const num is a Number. When adding these two constants together, the result is a String: ‘3Im a string’.
The syntax for applying the typeof operator is straightforward- simply add the typeof keyword to the left of the expression whose type you wish to check. You can also wrap the expression in parentheses, should you so desire.
The syntax of the typeof operator is:
typeof operand
- operand: an expression whose type you wish to reveal
The following examples demonstrate the return value of the typeof operator when it is applied to different JavaScript data types
Number
const num = 3; console.log(typeof num); // Expected output: number
BigInt
const bigNum = 1087874764675896857925344n; console.log(typeof bigNum); // Expected output: bigint
Boolean
const b = true; console.log(typeof b); // Expected output: boolean
undefined
const x = undefined; console.log(typeof x); // Expected output: undefined
Symbol
const sym = Symbol('foo'); console.log(typeof sym); // Expected output: symbol
Object
const obj = {}; console.log(typeof obj); // Expected output: object
Array
const arr = []; console.log(typeof arr); // Expected output: object
Note: the type of Array is Object!
Tip: To detect if an expression is an array, use the Array.isArray() method.
console.log(Array.isArray(arr)); // Expected output: true
Function
const f = function () { return 'Im a function' }; console.log(typeof f); // Expected output: function
null
const n = null; console.log(typeof n); // Expected output: object
Note: the type of null is Object!
Related Articles
JavaScript – Data types explained