Skip to main content

Command Palette

Search for a command to run...

How to check for an empty/undefined/null string in JavaScript?

Javascript | string | check | how to

Published
1 min read
V

Graduated with a Master’s degree in Software Engineering from San Jose State University in December 2019 and currently working at PayPal on the Customer Journey Platform. I enjoy generating new ideas and devising feasible solutions to broadly relevant problems. My colleagues would describe me as a driven, resourceful individual who maintains a positive, proactive attitude when faced with adversity. Interested to work in areas related to Distributed Systems, Cloud Infrastructure and Micro-Services. I get a lot of satisfaction from the constant learning and puzzle solving that comes with my profession and contributing to a successful and worthwhile product. My expertise includes project design and management, data analysis and interpretation, and the development and implementation of software products.

  1. To check for a truthy value:
if (strValue) {
    // strValue was non-empty string, true, 42, Infinity, [], ...
}
  1. To check for a falsy value:
if (!strValue) {
    // strValue was empty string, false, 0, null, undefined, ...
}
  1. Empty string (only!)

To check for exactly an empty string, compare for strict equality against "" using the === operator:

if (strValue === "") {
    // strValue was empty string
}
  1. To check for not an empty string strictly, use the !== operator:
if (strValue !== "") {
    // strValue was not an empty string
}
  1. Using type casting:
if (Boolean(str)) {
    // Code here
}

Typecast the variable to Boolean, where str is a variable.

  • It returns false for null, undefined, 0, 000, "", false.

  • It returns true for all string values other than the empty string (including strings like "0" and " ")

How Tos

Part 1 of 8

Compilation of tips and recipes to increase your programming skills.

Up next

How to programmatically copy to the clipboard in JavaScript?

Javascript | copy | clipboard | how to