Dan D Kim

Let's share stories

Is it a string? Really? (A must-know for a Javascript developer)

2019-12-09 Dan D. Kimjavascript

I’m no senior Javascript developer, but I think there is one thing all JS developers need to know.

It’s the difference between typeof and instanceof.

typeof vs instanceof

What is it

Allow me to throw this example at you:

const a = 'hello'
const b = new String('there')

typeof a // "string"
typeof b // "object"

a instanceof String // false
b instanceof String // true

Now let me explain.

typeof returns the type of the operand (reference)

instanceof takes an object and evaluates if it contains the prototype property of the constructor. If you don’t know what that means, it basically returns true if the object has been created with the specified constructor. You might want to read up on the prototype chain for more details. (reference).

Why is it important

It’s important because you might be improperly detecting operand types.

Let’s say you need to implement a function to detect if the argument is of type string.

function isString (arg) {
    if (...) {
        return true
    } else {
        return false
    }
}

Without knowing about the typeof vs instanceof, you might erratically only use one of them, like so:

function isString (arg) {
    if (typeof arg === 'string') {
        return true
    } else {
        return false
    }
}

isString('dandy') // true
isString(new String('blog')) // false

Make sure you use both typeof and instanceof

The proper way to be to use both comparisons.

function isString (arg) {
    if (typeof arg === 'string' || arg instanceof String) {
        return true
    } else {
        return false
    }
}

This way, you have a reliable function that will accurately evaluate whether the operand is a string.

It might be annoying, but it's what we have and it's worth the trouble

In my experience, strings are usually instantiated as a prototype, and never as an object. It’s when you work with 3rd party APIs that you have to use caution. Still, better safe than sorry.

That’s all. Hope you learned something. Happy developing :)