How to check if a variable is a string in JavaScript?
Hello everyone! I'm new to JavaScript and ran into a problem. I have a function that should only work with string values. If I pass a number or an object, everything breaks. I'm trying to check the variable type using typeof, but the results confuse me.
Here's an example of my code:
```javascript
function processInput(input) {
if (typeof input === 'string') {
console.log('This is a string, length: ' + input.length);
} else {
console.log('This is not a string!');
}
}
processInput('Hello'); // Works: "This is a string, length: 5"
processInput(42); // Works: "This is not a string!"
processInput(new String('Test')); // Outputs "This is not a string!" — but I expected it to be a string!
processInput(null); // Outputs "This is not a string!" — ok
processInput(undefined); // Outputs "Th
No answers yet.
Log in to leave an answer
Blogs
Java for Machine Learning: Capabilities and Limitations in Practice
Monitoring Java Applications: Metrics and Alerts (Advanced Level)
Kotlin in 2025: What's New? A Practical Overview for Developers
Salaries of Swift Developers in Russia: Market Overview for Advanced