Javascript проверка пустых значений

JavaScript Check Empty String – Checking Null or Empty in JS

Joel Olawanle

Joel Olawanle

JavaScript Check Empty String – Checking Null or Empty in JS

There are a number of reasons why you might need to check if a string is empty or not. One of the most important reasons is when you’re retrieving data from a database, API, or input field.

In this article, you will learn how to check if a sting is empty or null in JavaScript. We will see many examples and methods you can use so that you can understand them and decide which one to use and when.

What’s the Difference Between Null and Empty?

Before we begin, you need to understand what the terms Null and Empty mean, and understand that they are not synonymous.

For example, if we declare a variable and assign it an empty string, and then declare another variable and assign it the Null value, we can tell them apart by looking at their datatype:

let myStr1 = ""; let myStr2 = null; console.log(typeof myStr1); // "string" console.log(typeof myStr2); // "object" 

Looking at the code above, we can see that the compiler/computer interprets each value differently. So when it comes time to check, we must pass conditions for both types of values because we as humans frequently refer to null as empty.

How to Check for Empty or Null in JavaScript

We now know that an empty string is one that contains no characters. It is very simple to check if a string is empty. We can use two major methods that are somewhat similar because we will use the strict equality operator ( == ).

How to Check for an Empty String in JavaScript with the length Property

In this first method, we will check for the length of the string by adding the length property. We’ll check if the length is equal to 0 . If it’s equal to zero, it means that the string is empty, as we can see below:

let myStr = ""; if (myStr.length === 0)

The above will return this:

But this approach unfortunately might not work in all situations. For example, if we have a string that has white spaces as seen below:

let myStr = " "; if (myStr.length === 0) < console.log("This is an empty string!"); >else
"This is NOT an empty string!" 

We can easily fix this error by first removing the white spaces using the trim() method before checking for the length of such string to see if it’s empty as seen below:

let myStr = " "; if (myStr.trim().length === 0) < console.log("This is an empty string!"); >else

This will now return the following:

Note: If the value is null, this will throw an error because the length property does not work for null.

Читайте также:  Добавить в исключение java

To fix this, we can add an argument that checks if the value’s type is a string and skips this check if it is not:

let myStr = null; if (typeof myStr === "string" && myStr.trim().length === 0)

How to Check for an Empty String in JavaScript by String Comparison

Another way to check if a string is empty is by comparing the string to an empty string.

As with the previous method, if we have white spaces, this will not read the string as empty. So we must first use the trim() method to remove all forms of whitespace:

let myStr = " "; if (myStr.trim() === "") < console.log("This is an empty string!"); >else

Just as we did for the length method, we can also check for the type of the value so that this will only run when the value is a string:

let myStr = null; if (typeof myStr === "string" && myStr.trim() === "")

How to Check for Null in JavaScript

So far, we’ve seen how to check if a string is empty using the length and comparison methods.

Now, let’s see how to check if it’s null , and then check for both. To check for null , we simply compare that variable to null itself as follows:

let myStr = null; if (myStr === null)

How to Check for a Null or Empty String in JavaScript

At this point we have learned how to check for an empty string and also if a variable is set is null. Let’s now check to for both this way:

let myStr = null; if (myStr === null || myStr.trim() === "") < console.log("This is an empty string!"); >else

Conclusion

In this article, we learned how to check for an empty string or null and why they are not the same thing.

Источник

How to Check for Empty/Undefined/Null String in JavaScript

In JavaScript, one of the everyday tasks while validating data is to ensure that a variable, meant to be string, obtains a valid value.

This snippet will guide you in finding the ways of checking whether the string is empty , undefined , or null .

If you want to check whether the string is empty/null/undefined, use the following code:

let emptyStr; if (!emptyStr) < // String is empty >

w3docs logo

Javascript empty string

When the string is not null or undefined, and you intend to check for an empty one, you can use the length property of the string prototype, as follows:

w3docs logo

Javascript empty string

Another option is checking the empty string with the comparison operator “===” .

It’s visualized in the following example:

w3docs logo

Javascript empty string

Description of Strings in JavaScript

The JavaScript strings are generally applied for either storing or manipulating text. There is no separate for a single character. The internal format of the strings is considered UTF-16.

Another vital thing to know is that string presents zero or more characters written in quotes.

Usage of the Length Property in JavaScript

The “length” property is an essential JavaScript property, used for returning the number of function parameters. Also, the “length” property can be used for introspecting in the functions that operate on other functions.

Comparison Operators in JavaScript

Comparison operators are probably familiar to you from math.

So, they are the following:

  • Less than ( ) : returns true when the value on the left is greater than the one on the right. Otherwise, it will return false.
  • Less than or equal to ( =) : returns true when the value on the left is greater or equal to the one on the right. In another way, it will return false.
  • Equal to (===) : returns true when the value on the left is equal to the one on the right. Otherwise, it will return false.
  • Not equal to (!==) : returns true when the value on the left is not equal to the one on the right. In another way, it will return false.
Читайте также:  Загрузка обрезка изображения php

Источник

Функция для проверки на null, undefined или пустые переменные в JavaScript

Filtering null, undefined or empty values in JavaScript.

В JavaScript, есть случаи, когда необходимо проверить, имеет ли переменная какое-либо значение или она является null , undefined или пустым значением. Особенно это актуально при обработке входных данных или при работе с внешними API.

Допустим, есть код, который обрабатывает данные, пришедшие из внешнего источника. Но эти данные могут быть непредсказуемыми, и иногда они могут быть null , undefined или просто пустыми. Это может привести к непредвиденным ошибкам в коде.

let data = getDataFromSource(); // может вернуть любое значение processData(data); // если data является null, undefined или пустым, здесь может произойти ошибка

В таких случаях, может быть полезно иметь универсальную функцию, которая проверяет, имеет ли переменная какое-либо значение или она является null , undefined или пустым значением.

Эта функция возвращает false , если значение val является undefined , null или пустой строкой, и true во всех остальных случаях.

Теперь, используя эту функцию, можно сделать код более безопасным:

let data = getDataFromSource(); // может вернуть любое значение if (isValue(data)) < processData(data); // будет вызвано только если data имеет значение >else < handleEmptyData(); // обрабатывает ситуацию, когда data не имеет значения >

Таким образом, функция проверки на null , undefined или пустые значения может быть полезной для обеспечения безопасности и надежности кода.

Источник

How to Check if an Object is Empty in JavaScript – JS Java isEmpty Equivalent

Joel Olawanle

Joel Olawanle

How to Check if an Object is Empty in JavaScript – JS Java isEmpty Equivalent

An object is one of the most commonly used data types in programming. An object is a collection of related data stored as key-value pairs. For example:

When working with objects, you may need to check if an object is empty before performing a function.

In JavaScript, there are various ways you can check if an object is empty. In this article, you will learn the various ways you can do this, the options that can be attached, and why.

Note: An object is considered empty when it has no key-value pair.

In case you are in a rush, here is a basic example:

const myEmptyObj = <>; // Works best with new browsers Object.keys(myEmptyObj).length === 0 && myEmptyObj.constructor === Object // Works with all browsers _.isEmpty(myEmptyObj) 

Both methods will return true . Let’s now understand these and more options you can use to check if an object is empty in JavaScript.

How to Check if an Object is Empty with Object.keys()

The Object.keys() method is a static object method introduced in ECMAScript6 (ES6) and is supported in all modern browsers. This method returns an array with the keys of an object. For example:

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; console.log(Object.keys(userDetails)); // ["name","username","age"] 

With this, you can now apply the .length property. If it returns zero (0), the object is empty.

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; console.log(Object.keys(userDetails).length); // 3 console.log(Object.keys(myEmptyObj).length); // 0 

You can now use this method to check if an object is empty with an if statement or create a function that checks.

const isObjectEmpty = (objectName) =>

This will return either true or false . If the object is empty, it will return true , otherwise, it will return false .

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; const isObjectEmpty = (objectName) => < return Object.keys(objectName).length === 0 >console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true 

Note: Checking the length alone is not the best option when checking if an object is empty or for any datatype. It is always best to confirm if the data type is correct.

To do this, you can use the constructor check:

const isObjectEmpty = (objectName) =>

This way, you are liable to get a more thorough check.

Читайте также:  Фоновое изображение с помощью HTML

Thus far, everything has worked fine. But you might also want to avoid throwing a TypeError when a variable is undefined or a value of null is passed instead of <> . To fix this, you can add an extra check:

const isObjectEmpty = (objectName) => < return ( objectName && Object.keys(objectName).length === 0 && objectName.constructor === Object ); >; 

In the code above, an extra check is added. This means that it will return either null or undefined if it is not an empty object, as shown in the example below:

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; let nullObj = null; let undefinedObj; const isObjectEmpty = (objectName) => < return ( objectName && Object.keys(objectName).length === 0 && objectName.constructor === Object ); >; console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true console.log(isObjectEmpty(undefinedObj)); // undefined console.log(isObjectEmpty(nullObj)); // null 

Note: This applies to other object static methods, meaning you can make use of Object.entries() or Object.values() instead of Object.keys() .

How to Check if an Object is Empty with a for…in Loop

Another method you can use is the ES6 for…in loop. You can use this loop alongside the hasOwnProperty() method.

const isObjectEmpty = (objectName) => < for (let prop in objectName) < if (objectName.hasOwnProperty(prop)) < return false; >> return true; >; 

The method above will loop through each object property. If it finds a single iteration, the object is not empty. Also, the hasOwnProperty() will return a boolean indicating whether the object has the specified property as its property.

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; const isObjectEmpty = (objectName) => < for (let prop in objectName) < if (objectName.hasOwnProperty(prop)) < return false; >> return true; >; console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true 

How to Check if an Object is Empty with JSON.stringify()

You can also make use of the JSON.stingify() method, which is used to convert a JavaScript value to a JSON string. This means it will convert your object values to a sting of the object. For example:

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; console.log(JSON.stringify(userDetails)); Output: "" 

This means when it is an empty object, then it will return «<>» . You can make use of this to check for an empty object.

const isObjectEmpty = (objectName) => < return JSON.stringify(objectName) === "<>"; >; 

This will return true if the object is empty, otherwise false :

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; const isObjectEmpty = (objectName) => < return JSON.stringify(objectName) === "<>"; >; console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true 

How to Check if an Object is Empty with Lodash

Finally, some of the methods I’ve explained here might work for older browser versions, while others may not work. If you are concerned about a solution that will work for both old and modern browser versions, you can use Lodash.

Lodash is a modern JavaScript utility library that can perform many JavaScript functionalities with very basic syntax.

For example, if you want to check if an object is empty, you only need to use the «isEmpty» method.

Installing Lodash into your project is quite easy. All you have to do is make use of this command:

You can now initialize the underscore method and make use of this method.

const _ = require('lodash'); let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; const isObjectEmpty = (objectName) => < return _.isEmpty(objectName); >; console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true 

That’s It! 💪

I’ve enjoyed exploring the various ways you can check if an object is empty. Feel free to use the best method that fits your project or task.

Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.

Источник

Оцените статью