In this write-up, we will learn all about the typeof operator, what it is and how to use it; but first, we need to understand what data types are.
What are data types:
Data types are a classification of data that defines how data can be stored and manipulated. Each programming language has built-in data types which might be different from other programming languages.
- Number: As the name implies, it consists of numbers
- Boolean: Booleans can have only two different values; true or false.
- String: Strings are a collection of alphanumeric characters.
- Undefined: Empty or undeclared variable.
- Object: Bundle/Collection of Data
The typeof is not a function, but rather it is an operator. In programming languages, functions and operators are different; they may behave similarly but are synthetically and semantically different.
How to use typeof operator:
A variable is passed to the typeof operator as a parameter and returns the variable’s datatype.
Both of the syntaxes mentioned above are correct. The operand can be written with or without parentheses.
Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console:
- Use the F12 key in Chrome and other chromium-based browsers.
- Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla.
- Use Option + ⌘ + C keyboard shortcut keys in Safari (if the developer menu does not appear, open Preferences by pressing ⌘ + , and in the Advanced tab, check “Show Develop menu in menu bar”).
In the code given below, we have declared a variable named age and assigned it a value of 10. Then we used the typeof operator to determine the datatype of age. The typeof operator was put inside console.log() to output the return value of the typeof operator on the console.
If we assign a new value to age, i.e., ten instead of 10, then the output changes to:
Now, if we do not assign any value to age and use the typeof operator on it; then the operator will return the following value:
We can use the same method to determine other data types as well like boolean, object and symbol, etc.:
As you have already seen in the above examples, the typeof operator can be combined with other functions and methods such as conolse.log. It can also be combined with conditionals, loops, etc.
In the example given below, the typeof operator is used with conditional statements:
if (typeof(age) == 'number')
console.log('The provided number is in the form of digits.')
console.log('The provided number is not in the form of digits.')
Now, if we change the age from 5 to five, then the output changes to: