In this article, How to Check the Type of a Variable or Object in JavaScript? In JavaScript, the typeof operator is used to determine the typeof an object or variable. JavaScript, on the other hand, is a dynamically typed (or weakly typed) language. This indicates that a variable can have any type of value. The type of the value assigned to a variable determines the type of the variable.
The typeof operator in JavaScript allows you to determine the type of value or type of value that a variable contains . There is just one operand for the typeof operator (a unary operator), which takes one variable as input. It determines the operand’s type and a string is returned as a result.
Let’s understand the typeof operator using some examples:
Example 1: If a string variable is checked by typeof, the result will be “string”.
Javascript
<script> var apple = "apple" ; console.log( typeof apple); </script> |
Output:
"string"
Example 2: When we check the type of a number variable it results in the string “number”.
Javascript
<script> var number = 2052021; console.log( typeof number); </script> |
Output:
"number"
Example 3: When we check the type of undefined it is “undefined”.
Javascript
<script> console.log( typeof undefined); </script> |
Output:
"undefined"
Example 4: The type of special symbol is “string”.
HTML
< script > var symbol = "@"; console.log(typeof symbol); </ script > |
Output:
"string"
Example 5: The type of null is “object”.
HTML
< script > console.log(typeof null); </ script > |
Output:
"object"
Example 6: The type of NaN ( not a number ) returns “number”.
Javascript
<script> console.log( typeof NaN); </script> |
Output:
"number"
Example 7: In this example, a new object is created using a new keyword. typeof the variable created as “object”.
Javascript
<script> let obj = new String( "this is a string" ) console.log( typeof obj); </script> |
Output:
"object"
Example 8: In the below example, a function is created to find the sum of two numbers and is passed on to a variable. type of the function variable is “function”.
Javascript
<script> let func_object = function (a, b) { return a + b; }; console.log( typeof func_object); </script> |
Output:
"function"