Explain Codes LogoExplain Codes Logo

Check if a variable is a string in JavaScript

javascript
string-validation
best-practices
unit-testing
Anton ShumikhinbyAnton ShumikhinΒ·Aug 16, 2024
⚑TLDR

To identify a string, leverage typeof:

if (typeof myVar === 'string') { // Great, it's a string! }

Do a more thorough string identification by combining typeof and instanceof:

if (typeof myVar === 'string' || myVar instanceof String) { // It's definitely a string or a string object, no joking now! 😎 }

Solid check with Object.prototype.toString

When battling with those perplexing objects or dealing with prototype sorcery, Object.prototype.toString.call() comes to rescue like a true superhero, returning a robust [object String] for a certified string scenario.

if (Object.prototype.toString.call(myVar) === '[object String]') { // String identity confirmed! Pin a badge on it! }

String validation with external libraries

Both lodash and jQuery have their own armory for battling the "Is this a string?" question. With lodash, you'd wield _.isString(myVar). Brandishing jQuery, you'd defend with $.type(myVar) === "string". Clear, concise, and probably a tad cooler!

Maneuvering potential pitfalls and corner cases

A fair warning, my friend: Using typeof on a new String("example") returns you 'object'. Say what? Yes, it sees a string object and calls it an 'object'. And believe me or not, typeof can't tell a regular string from a disguised string (like a proxy around a string). Combining typeof with Object.prototype.toString.call() helps you outsmart these tricksy cases.

Differentiating primitive strings and String objects

// "It's not a string. It's a primitive string!" πŸ•΅οΈβ€β™‚οΈ if (typeof myVar === 'string') { console.log('Primitive string'); } // Identifying a String object feels like meeting a celebrity in the wild if (myVar instanceof String) { console.log('String object'); } // Now, the ultimate string-or-object check, the Swiss knife in your toolset // If Sherlock Holmes wrote JavaScript, he's definitely using this! if (typeof myVar === 'string' || myVar instanceof String) { console.log('It’s either a primitive string or a String object'); }

Respecting best practices

Google and Douglas Crockford suggest to avoid using string object wrappers like new String(). They don't improve your JavaScript balance but sure do contribute to the tricky parts. So, let's stick to primitive strings and enjoy a life with fewer surprises!

The power of unit testing

Conducting unit tests ensures that your string recognition logic holds water. Test it in diverse scenarios. Proxies? Check. Falsy values? Check. Objects trying to fool you into thinking they're strings? Check. False alarms and misses? Consider them beaten!