Tuesday 29 October 2024

Understanding the typeof Operator in JavaScript with examples

The typeof operator in JavaScript is used to determine the type of a given value or variable. It returns a string indicating the type of the operand. The typeof operator is particularly useful for checking the data type before performing operations or when debugging code.

Syntax

typeof operand

 

operand: The value or variable whose type you want to check.

 

Let's go through the various data types in JavaScript and see what the typeof operator returns for each.

 

1. Primitive Types

String: A sequence of characters enclosed in quotes (single, double, or backticks).

 

string.js

let str = "Hello, World!";
console.log(typeof str); // Output: "string"

 

Output

String

 

Number: Represents both integers and floating-point numbers.

 

number.js

let num = 42;
console.log(typeof num); // Output: "number"

let floatNum = 3.14;
console.log(typeof floatNum); // Output: "number"

 

Output

number
number

 

Boolean: Represents a logical entity and can have two values: true or false.

 

boolean.js

let isActive = true;
console.log(typeof isActive); // Output: "boolean"

 

Output

boolean

 

Undefined: A variable that has been declared but not assigned a value.

 

undefined.js

let undefinedVar;
console.log(typeof undefinedVar); // Output: "undefined"

 

Output

undefined

 

Symbol: Introduced in ECMAScript 2015 (ES6), a Symbol is a unique and immutable primitive value.

 

symbol.js

 

let sym = Symbol('unique');
console.log(typeof sym); // Output: "symbol"

Output

symbol

BigInt: Introduced in ECMAScript 2020, BigInt is used for integers that are too large to be represented by the Number type.

 

bigint.js

let bigIntNum = 123456789012345678901234567890n;
console.log(typeof bigIntNum); // Output: "bigint"

Output

Bigint

 

2. Object Types

Object: A collection of key-value pairs. Objects include arrays, functions, dates, etc. Arrays are objects in JavaScript, so the typeof operator returns "object" for arrays as well. Functions are also objects in JavaScript, but the typeof operator returns "function" for functions. The typeof operator returns "object" for date objects as well.

 

objects.js

let obj = { name: "Alice", age: 30 };
console.log(typeof obj); // Output: "object"

let arr = [1, 2, 3, 4];
console.log(typeof arr); // Output: "object"

function greet() {
  return "Hello!";
}
console.log(typeof greet); // Output: "function"

let date = new Date();
console.log(typeof date); // Output: "object"

Output

object
object
function
object

Points to remember

1.   typeof null returns "object"

2.   Even though functions are technically objects, typeof treats them as a special case and returns "function".

3.   type of an undeclared variable returns "undefined"

 

Usecase 1: Checking for Numbers Before Performing Arithmetic Operations.

 

usecase1.js

function addNumbers(a, b) {
  if (typeof a !== "number" || typeof b !== "number") {
    throw new Error("Both arguments must be numbers");
  }
  return a + b;
}

try {
  let x = 10;
  let y = "5";
  console.log(addNumbers(x, y)); // This will throw an error
} catch (error) {
  console.error(error.message);
}

Output

Both arguments must be numbers

 

Usecase 2: Handling Different Types in Functions.

 

usecase2.js

function processInput(input) {
  if (typeof input === "string") {
    console.log("Processing string...");
  } else if (typeof input === "number") {
    console.log("Processing number...");
  } else if (typeof input === "boolean") {
    console.log("Processing boolean...");
  } else if (typeof input === "undefined") {
    console.log("Processing undefined...");
  } else if (typeof input === "object") {
    if (input === null) {
      console.log("Processing null...");
    } else if (Array.isArray(input)) {
      console.log("Processing array...");
    } else {
      console.log("Processing object...");
    }
  } else if (typeof input === "function") {
    console.log("Processing function...");
  } else if (typeof input === "symbol") {
    console.log("Processing symbol...");
  } else if (typeof input === "bigint") {
    console.log("Processing bigint...");
  } else {
    console.log("Unsupported type");
  }
}

// Test cases
processInput(42);                   // Output: Processing number...
processInput("Hello");              // Output: Processing string...
processInput(true);                 // Output: Processing boolean...
processInput(undefined);            // Output: Processing undefined...
processInput(null);                 // Output: Processing null...
processInput({ name: "Alice" });    // Output: Processing object...
processInput([1, 2, 3]);            // Output: Processing array...
processInput(function() {});        // Output: Processing function...
processInput(Symbol("unique"));     // Output: Processing symbol...
processInput(12345678901234567890n);// Output: Processing bigint...

Output

Processing number...
Processing string...
Processing boolean...
Processing undefined...
Processing null...
Processing object...
Processing array...
Processing function...
Processing symbol...
Processing bigint...


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment