0
0
Javascriptprogramming~5 mins

Type checking using typeof in Javascript

Choose your learning style9 modes available
Introduction

We use typeof to find out what kind of value a variable holds. This helps us avoid mistakes when working with different types of data.

When you want to check if a variable holds a number before doing math.
When you want to make sure a value is a string before joining it with other text.
When you want to confirm if a variable is a boolean to control program flow.
When you want to check if a variable is undefined to avoid errors.
When debugging to understand what type of data your program is handling.
Syntax
Javascript
typeof variableName

typeof returns a string describing the type, like "number", "string", "boolean", "undefined", "object", or "function".

You can use it directly in conditions to decide what to do based on the type.

Examples
Checks the type of a number literal.
Javascript
typeof 42 // returns "number"
Checks the type of a text string.
Javascript
typeof "hello" // returns "string"
Checks the type of a true/false value.
Javascript
typeof true // returns "boolean"
Checks the type of a variable that has no value yet.
Javascript
typeof undefinedVariable // returns "undefined"
Sample Program

This program shows how typeof tells us the type of different values stored in the same variable.

Javascript
let value = 100;
console.log(typeof value); // number

value = "JavaScript";
console.log(typeof value); // string

value = false;
console.log(typeof value); // boolean

value = undefined;
console.log(typeof value); // undefined

value = { name: "Alice" };
console.log(typeof value); // object

value = function() {};
console.log(typeof value); // function
OutputSuccess
Important Notes

typeof null returns "object" which is a known quirk in JavaScript.

Arrays are also of type "object" when checked with typeof.

Use typeof when you want a quick check of simple types.

Summary

typeof helps you find out the type of a value.

It returns a string like "number", "string", "boolean", "undefined", "object", or "function".

Use it to avoid errors by checking types before working with values.