2.7 Module 2 · Variables, Data Types & Functions

Type Checking

Learn how to identify what kind of data you are working with at runtime — using typeof, instanceof, and Array.isArray() — and how to validate inputs before operating on them.

1

Definition

Type Checking in JavaScript is the process of identifying the data type of a variable or value during runtime. It is commonly done using operators like typeof and instanceof, along with validation techniques to ensure correct data handling before performing operations.

Because JavaScript is dynamically typed — variables can hold any type at any time — type checking is an essential defensive practice that prevents silent bugs caused by operating on unexpected data.

2

Simple Way

Type checking asks: "What type of data is this?" — and uses the right tool depending on what you need to verify:

typeof Returns a string describing the primitive type — "number", "string", "boolean"
instanceof Checks if an object was created from a specific constructor — e.g. Array, Object
Array.isArray The most reliable way to confirm a value is an array (returns true / false)
3

Code Examples

Example 1 — Using typeof
let name      = "Aman";
let age       = 22;
let isStudent = true;

console.log(typeof name);       // "string"
console.log(typeof age);        // "number"
console.log(typeof isStudent);  // "boolean"
Output
Click ▶ Run to execute
Explanation
  • typeof is an operator — it returns a lowercase string naming the type
  • Works well for all primitives: "string", "number", "boolean", "undefined", "symbol", "bigint"
  • Use === "number" (strict) when comparing — never ==
Example 2 — Special typeof Cases
console.log(typeof null);       // "object" — historic JS bug
console.log(typeof undefined);  // "undefined"
console.log(typeof []);         // "object" — arrays are objects
console.log(typeof {});         // "object"
console.log(typeof function(){}); // "function"
Output
Click ▶ Run — some of these will surprise you!
Explanation
  • typeof null === "object" is a well-known JavaScript bug — use value === null to check for null
  • typeof [] and typeof {} both return "object" — use Array.isArray() to tell them apart
  • typeof function(){} uniquely returns "function"
Example 3 — Using instanceof
let arr = [1, 2, 3];
let obj = { name: "Aman" };
let now = new Date();

console.log(arr instanceof Array);   // true
console.log(obj instanceof Object);  // true
console.log(arr instanceof Object);  // true — arrays are objects too
console.log(now instanceof Date);    // true
Output
Click ▶ Run to execute
Explanation
  • instanceof checks the prototype chain — it confirms what constructor created the value
  • Arrays are also objects, so arr instanceof Object is true
  • Useful for built-in types like Date, Map, Set that typeof cannot distinguish
Example 4 — Array.isArray() (Best Practice)
let arr  = [1, 2, 3];
let obj  = { a: 1 };
let num  = 42;

console.log(Array.isArray(arr));  // true
console.log(Array.isArray(obj));  // false
console.log(Array.isArray(num));  // false
Output
Click ▶ Run to execute
Explanation
  • Array.isArray() is the only reliable way to detect an array — both typeof and instanceof have edge cases
  • Returns a clean true or false — no string parsing needed
  • Works correctly even across different frames or environments where instanceof Array can fail
Example 5 — Input Validation with Type Checking
function checkNumber(value) {
  if (typeof value === "number" && !isNaN(value)) {
    console.log(value + " is a valid number");
  } else {
    console.log("Invalid input: " + typeof value + " given");
  }
}

checkNumber(10);    // valid
checkNumber("10");  // string — invalid
checkNumber(NaN);   // NaN — invalid
Output
Click ▶ Run to execute
Explanation
  • Combining typeof with isNaN() gives a robust number check — NaN has type "number" but is not a valid number
  • Type checking before operations prevents unexpected NaN results or string concatenation bugs
4

Real-Life Example

Think of a security check at an airport — the system verifies the type of every document before allowing entry:

typeof
The officer glances at the document — passport, ticket, or ID card?
instanceof
Scans the barcode — confirms it was issued by the right authority
Array.isArray
Dedicated luggage scanner — specifically built to detect one thing reliably
isNaN
Verifies the age field is actually a number, not a scribbled word
5

HTML + JavaScript Example

Click ▶ Preview, type any value into the box, and see all three type-checking methods report on it simultaneously.

Live in Browser — Type Checker
<!DOCTYPE html>
<html>
<head><title>Type Checking</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">

  <h2>Type Checker</h2>
  <input id="val" type="text" placeholder="Enter a value"
    style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;
           font-size:1rem;width:200px">
  <button onclick="checkType()"
    style="margin-left:8px;padding:8px 18px;background:#f7df1e;border:none;
           border-radius:6px;cursor:pointer;font-weight:700;font-size:1rem">
    Check
  </button>
  <div id="output" style="margin-top:16px;line-height:2.2;font-size:0.95rem"></div>

  <script>
    function checkType() {
      let raw = document.getElementById("val").value;

      // Try to convert to a number to test both string and number checks
      let asNum = Number(raw);

      document.getElementById("output").innerHTML =
        "<b>Raw input:</b> " + raw + "<br>" +
        "<b>typeof:</b> " + typeof raw + "<br>" +
        "<b>Array.isArray():</b> " + Array.isArray(raw) + "<br>" +
        "<b>isNaN(Number(input)):</b> " + isNaN(asNum) + "<br>" +
        "<b>Looks like a number?</b> " +
          (!isNaN(asNum) && raw !== "" ? "✅ Yes" : "❌ No");
    }
  </script>

</body>
</html>
Live Preview
6

Tasks (Practice)

Easy Task 1 — Check a variable's type
Starter code
let score = 95;
  • Print typeof score — confirm it returns "number"
  • Change the value to a string and run again — watch the type change
  • Try typeof null and typeof undefined — note the quirks
Medium Task 2 — Array detector function
Starter code
function isItAnArray(input) {
  // your code here
}

isItAnArray([1, 2, 3]);
isItAnArray({ a: 1 });
isItAnArray("hello");
  • Use Array.isArray() inside the function to check the input
  • Print "Array detected" if true, "Not an array: [type]" if false
  • Test with an array, a plain object, and a string
7

MCQs

Q1
What does typeof [] return?
console.log(typeof []);
Output
Run it to verify
  • A "array"
  • B "object"
  • C "list"
  • D "undefined"
💡 B is correct. Arrays are a subtype of objects in JavaScript, so typeof [] returns "object". Use Array.isArray() to correctly identify arrays.
Q2
Which method is the best way to check if a value is an array?
let arr = [1, 2, 3];

console.log(typeof arr);           // not reliable for arrays
console.log(Array.isArray(arr));   // best practice
Output
Run it to verify
  • A typeof
  • B instanceof
  • C Array.isArray()
  • D checkType()
💡 C is correct. Array.isArray() is the most reliable method — it correctly returns true for arrays and false for everything else, including plain objects and null.
Q3
What does typeof undefined return?
console.log(typeof undefined);
Output
Run it to verify
  • A "null"
  • B "undefined"
  • C "object"
  • D "number"
💡 B is correct. typeof undefined correctly returns the string "undefined" — unlike typeof null which incorrectly returns "object" due to a historic JS bug.
8

Pro Tips & Extra Knowledge

  • 01

    Always use strict equality (===) when comparing typeof results — the returned value is always a lowercase string:

    Strict typeof comparison
    let value = 42;
    
    // ✓ Correct — strict string comparison
    console.log(typeof value === "number"); // true
    
    // ✗ Wrong — typeof never returns "Number" (capital N)
    console.log(typeof value === "Number"); // false
    
    // ✗ Wrong — typeof [] is "object", not "array"
    console.log(typeof [] === "array");     // false
    Output
    Click ▶ Run to execute
  • 02

    Use isNaN() to validate numeric input — but always convert to a number first, since isNaN("abc") coerces and can give misleading results:

    Safe number validation
    function isValidNumber(val) {
      return typeof val === "number" && !isNaN(val);
    }
    
    console.log(isValidNumber(42));    // true
    console.log(isValidNumber(NaN));   // false — NaN is typeof "number" but invalid
    console.log(isValidNumber("42"));  // false — it's a string
    Output
    Click ▶ Run to execute
  • 03

    Use instanceof for built-in constructors like Date, Map, and Set that typeof cannot tell apart from plain objects:

    instanceof for built-in types
    let today = new Date();
    let scores = new Map();
    
    console.log(typeof today);           // "object" — not helpful
    console.log(today instanceof Date);  // true  — helpful
    
    console.log(typeof scores);          // "object"
    console.log(scores instanceof Map);  // true
    Output
    Click ▶ Run to execute
  • 04

    Build a type guard helper to reuse consistent type checks across your code instead of repeating typeof expressions everywhere:

    Reusable type guards
    const isString  = v => typeof v === "string";
    const isNumber  = v => typeof v === "number" && !isNaN(v);
    const isArray   = v => Array.isArray(v);
    
    console.log(isString("hello")); // true
    console.log(isNumber(42));      // true
    console.log(isNumber(NaN));     // false
    console.log(isArray([1, 2]));   // true
    Output
    Click ▶ Run to execute
Mini Challenge

Two different checks on the same array — predict what each one returns before running.

What does this print?
let arr = [1, 2, 3];

console.log(typeof arr);
console.log(arr instanceof Array);
Output
Think first, then run!
Step-by-Step Explanation
// arr = [1, 2, 3] — an array literal

// Line 1: typeof arr
//   typeof sees arr as a generic object — all non-primitive
//   reference types return "object" with typeof
//   Output → "object"

// Line 2: arr instanceof Array
//   instanceof checks the prototype chain
//   arr was created from the Array constructor → true
//   Output → true

// Final output:
//   "object"   ← typeof is not specific enough for arrays
//   true       ← instanceof correctly identifies it as an Array

// Key takeaway:
//   typeof and instanceof give different information.
//   For arrays, use Array.isArray() — it is the clearest:
//
//   console.log(Array.isArray(arr)); // true — unambiguous