Mark As Completed Discussion

Good evening! Here's our prompt for today.

Detecting JavaScript Data Types: A Universal Method

The Challenge

Imagine a universe of data types in JavaScript! It's a colorful world with characters like Array, ArrayBuffer, Map, Set, Date, and the mysterious Function. Your mission, should you choose to accept it, is to create a universal method that identifies these inhabitants by their data type name.

Constraints:

  • The function should take only one argument—the data object.
  • We want a universal approach; using multiple if conditions to list and detect each data type is a no-go.

Example Usage

For the function detectType(), the following should hold true:

JAVASCRIPT
1detectType(1);           // Output: 'number'
2detectType(new Map());   // Output: 'map'
3detectType([]);          // Output: 'array'
4detectType(null);        // Output: 'null'

Question

Try to solve this here or in Interactive Mode.

How do I practice this challenge?

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Here's how we would solve this problem...

How do I use this guide?

The Visual Insight

Picture your data types as distinct islands in an archipelago. Your function is the explorer boat that sails between these islands and reads the name sign at each dock. It doesn't matter which island you land on; you'll always find the right name!

Crafting the Solution

  1. Utilize JavaScript’s Native Typeof: Our first instinct might be to reach for JavaScript's built-in typeof operator. However, typeof lacks the specificity needed for custom and built-in objects like Array or Date. It often just returns 'object', which doesn't help us much.

  2. Object’s ToString Method: In JavaScript, the Object prototype has a toString method that, when called directly, provides more specific information than typeof.

A Deep Dive Into the Universal DataType Detector

How to Solve This: A Step-by-Step Guide

Step 1: Summon the Power of Object.prototype.toString

First, we call upon Object.prototype.toString.call(data). This incantation returns a raw string that holds clues about the data type.

Step 2: String Alchemy

Our next mission is to mine the useful nuggets—our data type—from this raw string.

The Code That Makes It All Happen

Behold the code that brings these steps to life.

JAVASCRIPT
1function detectType(data) {
2  const rawType = Object.prototype.toString.call(data);
3  return rawType.slice(8, -1).toLowerCase();
4}

The Under-the-Hood Mechanics

Our solution may look simple, yet it elegantly fulfills the requirement to be generic. We achieve this by invoking the Object.prototype.toString method, which acts like an oracle. The oracle speaks in riddles: it returns the data type enveloped in a string format like [object dataType].

Deciphering the Oracle's Message

The answer to our quest lies between the square brackets in the oracle's message. We slice this string to get that part. Then, to make it universally readable, we convert it to lowercase.

The Alternate Path

If you prefer another twist, you can modify the function to slice from the first character onward and then split the string using a space delimiter. This will still get you to the treasure—the data type.

JAVASCRIPT
1function detectType(data) {
2  return Object.prototype.toString
3    .call(data)
4    .slice(1, -1)
5    .split(" ")[1]
6    .toLowerCase();
7}

The Grand Conclusion

Now, you're equipped with a detectType function that's like a Swiss Army knife for data types. Not only does it elegantly solve the problem, but it also does so in a way that's adaptable to future challenges.

One Pager Cheat Sheet

  • Create a generic, parameter-accepting method that returns a string of the data type of the given input.
  • We can parse a given data's type by calling Object.prototype.toString() and slicing/splitting the result.

This is our final solution.

To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Alright, well done! Try another walk-through.

If you had any problems with this tutorial, check out the main forum thread here.