I’m trying to write a function that behaves differently based on the variable type. What and how should I use in JavaScript to reliably check if a given variable is a string or some other data type?
Been coding JavaScript for over a decade now, and honestly, the quickest way I check if a variable is a string is with typeof
.
if (typeof myVar === "string") {
console.log("Yep, it's a string!");
}
It’s clean and works most of the time — especially when you’re just dealing with string primitives. But heads up: it won’t catch instances where someone creates a string using new String()
. So, for basic needs, this handles your javascript is string check well.
Yep, I’ve run into those edge cases too in larger codebases. Coming from a backend-heavy environment, I’ve learned that sometimes people do use new String()
— and that’s where typeof
falls short.
if (myVar instanceof String) {
console.log("It's a String object.");
}
So, if your code deals with mixed input or libraries you don’t fully control, checking instanceof String
helps catch those wrapped strings. It complements the basic javascript is string logic and gives you more confidence in what you’re dealing with.
Working with a lot of API-driven data over the years, I’ve found combining both checks is the safest approach. Especially when the source of data is unpredictable.
if (typeof myVar === "string" || myVar instanceof String) {
console.log("Definitely a string!");
}
This combo covers both primitives and object-wrapped strings, so you’re protected no matter how the value came in. It’s the most reliable javascript is string check I’ve seen — great for those messy, real-world scenarios where clean data is a luxury.