#atom
ID: JS-003
Date: [Insert Date]
Content:
The typeof
operator in JavaScript is used to determine the type of a value or variable. It returns a string indicating the type of the operand.
Syntax:
typeof operand
Return Values:
"number"
for numbers (includingNaN
)."string"
for strings."boolean"
for booleans."undefined"
for undefined values."object"
for objects,null
, and arrays."function"
for functions."bigint"
for BigInt values."symbol"
for symbols.
Examples:
console.log(typeof 42); // "number"
console.log(typeof 'Hello'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (historical bug)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function() {}); // "function"
console.log(typeof BigInt(123)); // "bigint"
console.log(typeof Symbol('id')); // "symbol"
Common Use Cases:
-
Type Checking:
Ensure a variable is of the expected type before performing operations.if (typeof value === 'number') { console.log('Value is a number'); }
-
Debugging:
Log the type of a variable to debug unexpected behavior.console.log(typeof someVariable);
-
Handling Undefined Variables:
Check if a variable is defined before using it.if (typeof someVariable === 'undefined') { console.log('Variable is undefined'); }
Limitations:
- The
typeof null
returns"object"
, which is a historical bug in JavaScript. - Arrays are also considered objects, so
typeof []
returns"object"
.
Connections:
Connections:
Sources: