Discussion about this post

User's avatar
Richard's avatar

One slight niggle: your first example changes the behaviour of the code.

In the "before" code, the console.log statement only executes if user?.profile?.address?.city is not null. In the "modern" code, it always executes, so your console could be filled with "null" logs.

O.I.B.'s avatar

4. Use Object.prototype.toString.call() for Reliable Type Detection (for classes too)

function getType(value) {

if (value === null) return "Null";

if (typeof value === "object") {

return Object.getPrototypeOf(value)?.constructor?.name ?? "Object";

}

return Object.prototype.toString.call(value).slice(8, -1);

}

class User {}

console.log(getType(new User())); // "User"

console.log(getType(null)); // "Null"

console.log(getType('banana')); // "String"

console.log(getType([])); // "Array"

console.log(getType(Object.create(null))); // "Object"

1 more comment...

Ready for more?