23. Type Checking with typeof
The typeof operator is used to determine the data type of a variable or value. It returns a string representing the type.
Basic Usage
javascript let count = 5; let name = 'Dev'; let isReady = true; let data = null; let big = 1n;
console.log(typeof count); // Output: 'number' console.log(typeof name); // Output: 'string' console.log(typeof isReady); // Output: 'boolean' console.log(typeof undefined); // Output: 'undefined' console.log(typeof big); // Output: 'bigint'
// Functions are also considered objects in JS function greet() {}; console.log(typeof greet); // Output: 'function'
The null Anomaly Revisited
Remember the famous type error:
javascript console.log(typeof null); // Output: 'object' (A bug, but necessary to remember)
Checking for Objects (Excluding Null)
To safely check if something is a non-null object, you must combine checks:
javascript let myObj = { key: 'value' };
if (typeof myObj === 'object' && myObj !== null) { console.log('It is a valid object!'); }