JavaScript typeof Operator
Last Updated :
07 Mar, 2024
In JavaScript, typeof operator returns the data type of its operand in the form of a string. The operand can be any object, function, or variable.
Syntax:
typeof operand
// OR
typeof (operand)
Primitive Data Types
Primitive data types in JavaScript are basic data types that represent single values. They include:
- Number: Represents numeric values like integers and floating-point numbers.
- String: Represents textual data enclosed within single quotes (”) or double quotes (“”).
- Boolean: Represents true or false values.
- Undefined: Represents a variable that has been declared but has not been assigned a value.
- Null: Represents the intentional absence of any object value.
- Symbol: Represents a unique and immutable data type used as the key of an object’s property.
- BigInt: Represents large integers beyond the limit of the
Number
type.
typeof Operator Examples
Example 1: Below example show the results of typeof operator for premitive data types.
Javascript
const num = 10;
const str = "Hello" ;
const bool = true ;
const undef = undefined;
const nul = null ;
const sym = Symbol( "symbol" );
const bigInt = 9007199254740991n;
console.log( typeof num);
console.log( typeof str);
console.log( typeof bool);
console.log( typeof undef);
console.log( typeof nul);
console.log( typeof sym);
console.log( typeof bigInt);
|
Output
number
string
boolean
undefined
object
symbol
bigint
Example 2: This example uses ‘===’ (strict equality comparison operator) which compare value and type both and then return true or false.
javascript
console.log( typeof 25 === 'number' );
console.log( typeof 3.14 === 'number' );
console.log( typeof (69) === 'number' );
console.log( typeof Math.LN10 === 'number' );
console.log( typeof Infinity === 'number' );
console.log( typeof NaN === 'number' );
console.log( typeof Number( '100' ) === 'number' );
|
Explanation: In the first console.log(), the js starts compiling from left to right and it first calculates the type of 25 which is ‘number’, and then compares it with ‘number’ and then finally returns true or false accordingly.
Output
true
true
true
true
true
true
true
Example 3: This example compares the function datatype using the typeof operator.
javascript
console.log( typeof function () { } === 'function' );
console.log( typeof class C { } === 'function' );
console.log( typeof Math.sin === 'function' );
|
Share your thoughts in the comments
Please Login to comment...