How to properly check a string for empty value, null or undefined in JavaScript?
Hi everyone! I'm a beginner in JavaScript and writing a simple registration form. I need to check if the user entered a name, email, and password. But I keep getting confused with the checks and getting unexpected results.
Here's my current code:
```javascript
let userName = document.getElementById('name').value;
if (userName == '') {
console.log('Name is not filled');
} else {
console.log('Hello, ' + userName);
}
```
The problem is that if the user didn't enter anything, `userName` is an empty string `""`. But sometimes I get `null` or `undefined` (for example, if the element is not on the page, or I'm working with an API). I tried writing it like this:
```javascript
if (userName == null || userName == undefined || userName == '') {
// ...
}
```
But this looks bulky and ugly. Besides,
No answers yet.
Log in to leave an answer
Blogs
Working with Dates and Time in JavaScript: A Complete Guide for Node.js
Docker and PHP: Advanced Application Containerization Techniques
Rate Limiting and Throttling in C++: How to Protect Your API from Overloads
How to Open, Read, and Write Files in Python