Understanding Typeof in JavaScript

typeof is an operator used to determine the type of a given variable or value. It returns a string indicating the type.

Syntax: typeof operand

Example

let country = "India";
let continent = "Asia";
let population = 100;
let isIsland = false;
let language;
let state = null;
let district = NaN;
let numberArray = [1, 2, 3];

Log the values to the console

console.log(country);
console.log(continent);
console.log(population);
console.log(isIsland);
console.log(language);
console.log(state);
console.log(district);
console.log(numberArray);

Log the typeof the variables to console

console.log(typeof country);
console.log(typeof continent);
console.log(typeof population);
console.log(typeof isIsland);
console.log(typeof language);
console.log(typeof state);
console.log(typeof district);
console.log(typeof numberArray);
console.log(Array.isArray([]));

Results

console.log(typeof country); // string
console.log(typeof continent); // string
console.log(typeof population); // number
console.log(typeof isIsland); // boolean
console.log(typeof language); // undefined - undeclared variable returns "undefined"
console.log(typeof state); // object - typeof null returns "object"
console.log(typeof district); // number - typeof NaN returns "number" – NaN stands for "Not-a-Number" but is still classified as a number.
console.log(typeof numberArray); // object - Arrays and Objects both return "object"
console.log(Array.isArray([])); // true - To check if it's an Array

typeOf JavaScript output

Up Next
    Ebook Download
    View all
    Learn
    View all