Javascript typeof operator

The typeof operator in JavaScript is used to check the type of a value or a variable. It returns a string indicating the type, such as "number",  "string", "boolean",  "object",  "function",  "undefined", or "symbol".

Additional notes:

  • Use typeof for conditional logic based on data types.
  • Be aware of its limitations: it might not always provide the most precise information for complex objects.
  • Consider using instanceof for more specific type checks involving objects and their constructors.
Number:

 
let age = 30;
console.log(typeof age);   // Output: "number"
 
//typeof correctly identifies age as a number.
 
 

String:

 
let name = "Hi How are you?";
console.log(typeof name);  // Output: "string"
 
// typeof recognizes name as a string.

Boolean:

 
let isLoggedIn = true;
console.log(typeof isLoggedIn);  // Output: "boolean"
 
//  typeof determines that isLoggedIn is a boolean value.

Object (including arrays and null):

 
let person = {};  // Empty object
let colors = ["red", "green", "blue"];  // Array
let emptyValue = null;
 
console.log(typeof person);   // Output: "object"
console.log(typeof colors);   // Output: "object"
console.log(typeof emptyValue);  // Output: "object"
 
// Although arrays and null are different types, typeof returns "object" for all of them
 

Function:

 
function greet() {
    console.log("Hello!");
}
 
console.log(typeof greet);   // Output: "function"
 
// typeof correctly identifies greet as a function.