-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
In JavaScript, understanding the type of a value is just as important as working with the value itself. The typeof operator is a built-in tool that helps you identify the data type of a variable or expression at runtime. Since JavaScript is a dynamically typed language, variables can hold different types of values at different times. The typeof operator becomes especially useful in such situations to avoid unexpected behavior and bugs.
In this chapter, you will learn what the typeof operator is, why it is important, how it works with different data types, practical examples, common misunderstandings, best practices, and real-world use cases.
The typeof operator returns a string that indicates the type of the operand. It can be used with variables, literals, expressions, and even function calls.
typeof value
or
typeof(value)
Both forms are valid and widely used. The result is always a string such as "number", "string", or "boolean".
Because JavaScript automatically assigns types to variables, the type of a variable can change during execution. Checking types helps you ensure that your code behaves as expected.
Using typeof helps you:
Validate user input
Prevent runtime errors
Write flexible and reusable functions
Handle optional or dynamic values safely
Debug issues related to unexpected data types
When typeof is used with numeric values, it returns "number".
let ageAnanya = 22;
let heightMira = 5.4;
console.log(typeof ageAnanya); // number
console.log(typeof heightMira); // number
Even special numeric values return "number".
console.log(typeof Infinity); // number
console.log(typeof NaN); // number
Strings always return "string", regardless of how they are defined.
let firstName = "Ishita";
let city = 'Patna';
console.log(typeof firstName); // string
console.log(typeof city); // string
Boolean values return "boolean".
let isLoggedIn = true;
let hasAccess = false;
console.log(typeof isLoggedIn); // boolean
console.log(typeof hasAccess); // boolean
If a variable is declared but not assigned a value, typeof returns "undefined".
let score;
console.log(typeof score); // undefined
This also works safely even if a variable has not been declared at all.
console.log(typeof notDeclared); // undefined
This behavior prevents reference errors in many situations.
One of the most confusing results in JavaScript is when typeof is used with null.
let selectedCourse = null;
console.log(typeof selectedCourse); // object
Although null represents an empty or intentional absence of value, typeof null returns "object". This is a known behavior in JavaScript and should be handled carefully.
The BigInt data type returns "bigint" when checked using typeof.
let bigNumber = 12345678901234567890n;
console.log(typeof bigNumber); // bigint
Symbols return "symbol".
let uniqueId = Symbol("id");
console.log(typeof uniqueId); // symbol
Objects return "object" when checked using typeof.
let student = {
name: "Sanya",
age: 21
};
console.log(typeof student); // object
Arrays also return "object", which can be confusing for beginners.
let students = ["Ananya", "Ishita", "Mira"];
console.log(typeof students); // object
To specifically check for an array, additional methods are needed.
Functions return "function", which is a special case in JavaScript.
function greet(name) {
return "Hello " + name;
}
console.log(typeof greet); // function
This allows you to check whether a variable is callable before invoking it.
function addNumbers(a, b) {
if (typeof a === "number" && typeof b === "number") {
return a + b;
}
return "Invalid input";
}
console.log(addNumbers(10, 20));
console.log(addNumbers("10", 20));
let userAge = "22";
if (typeof userAge === "string") {
userAge = Number(userAge);
}
console.log(typeof userAge); // number
function greetUser(name) {
if (typeof name === "undefined") {
return "Hello Guest";
}
return "Hello " + name;
}
console.log(greetUser("Riya"));
console.log(greetUser());
let callback = function () {
return "Task completed";
};
if (typeof callback === "function") {
console.log(callback());
}
Assuming typeof null returns "null"
Expecting arrays to return "array"
Using typeof as the only method to detect objects
Forgetting that NaN is still a number
Use typeof for basic type checking
Combine typeof with other checks for arrays and null values
Always compare the result of typeof with a string
Use type checks in functions that accept dynamic input
The typeof operator is widely used in real-world applications:
Form validation to check input types
API response validation
Safely handling optional function parameters
Building utility functions that work with multiple data types
Debugging issues related to unexpected values
The typeof operator in JavaScript is a powerful and simple tool for identifying the type of a value at runtime. It works with all primitive and non-primitive data types and helps prevent errors caused by incorrect assumptions about data. While it has some known quirks, such as returning "object" for null and arrays, understanding these behaviors allows you to use typeof effectively. Mastering typeof is essential for writing safe, flexible, and robust JavaScript code.
Q1. How do you check the data type of the string "Welcome" using the typeof operator?
Q2. How do you find the type of a variable isOnline = true?
Q3. What will typeof 100 return, and how do you use it in a console log statement?
Q4. How do you check the type of an undefined variable let result; using typeof?
Q5. What does typeof null return, and why is it considered a JavaScript bug?
Q6. How do you use typeof to check if a function myFunc is of type "function"?
Q7. How do you determine if an array let colors = ["red", "blue"] is an object using typeof?
Q8. How do you use typeof to check the type of a BigInt value 123456789n?
Q9. How do you store the result of typeof in a variable and print it?
Q10. How do you check the type of a symbol declared as let sym = Symbol("key")?
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
