Checking if a variable is a string is something that we’ve to do a lot in JavaScript since JavaScript variables can store data of any type.
In this article, we’ll look at how we can check if a variable is a string in JavaScript.
The typeof Operator
The JavaScript typeof
operator is useful for checking if a variable is a string.
For instance, we can write:
const booleanValue = true;
const numericalValue = 123;
const stringValue = "abc";
const stringObject = new String("abc");
console.log(typeof booleanValue)
console.log(typeof numericalValue)
console.log(typeof stringValue)
console.log(typeof stringObject)
We use the typeof
operator before variables to check what they return.
The first console.log
should log 'boolean'
.
The 2nd console.log
should log 'boolean'
.
The 3rd console.log
should log 'string'
.
And the 4th console.log
should log 'object'
.
We shouldn’t use the String
constructor since it doesn’t return the type we expect for a string.
Instead, we should always use string literals.
toString
We can use a string’s toString
method to check if it’s a string.
For instance, we can write:
const booleanValue = true;
const numericalValue = 123;
const stringValue = "abc";
const stringObject = new String("abc");
const isString = (x) => { return Object.prototype.toString.call(x) === "[object String]" } console.log(isString(booleanValue)) console.log(isString(numericalValue)) console.log(isString(stringValue)) console.log(isString(stringObject))
We call `toString` from the `Object.prototype` with the parameter `x` and see if it returns `'[object String]'` .
If `x` is a string, then its `toString` method inherited from `Object.prototype` should return `'[object String']` .
Therefore, the first 2 console logs log `false` .
And the last 2 logs `true` .
### **Lodash**
Lodash has a `isString` method to check if a variable is a string.
For instance, we can write:
const booleanValue = true; const numericalValue = 123; const stringValue = "abc"; const stringObject = new String("abc");
console.log(_.isString(booleanValue))
console.log(_.isString(numericalValue))
console.log(_.isString(stringValue))
console.log(_.isString(stringObject))
```
It works with both string literals and string wrapper objects, so the first 2 console log log `false` .
And the last 2 log `true` .
### Conclusion
There are many ways to check whether a JavaScript variable holds a string.
One way is to use the `typeof` operator. The other to check the return result of `toString` .
Lodash also has the `isString` method to check if a variable is a string.