Checking null object in javascript

An Essential Guide to JavaScript null

Summary: in this tutorial, you’ll learn about the JavaScript null and how to handle it effectively.

What is null in JavaScript

JavaScript null is a primitive type that contains a special value null .

JavaScript uses the null value to represent the intentional absence of any object value.

If you find a variable or a function that returns null , it means that the expected object couldn’t be created.

The following example defines the Circle class whose constructor accepts an argument radius . The Circle class has a static method called create() that returns a new Circle object with a specified radius.

class Circle < constructor(radius) < this.radius = radius; > get area() < return Math.PI * Math.pow(this.radius, 2); > static create(radius) < return radius > 0 ? new Circle(radius) : null ; > >Code language: JavaScript (javascript)

This creates a new Circle object with the radius 10 :

let c = Circle.create(10); console.log(c.area); // 31.41592653589793Code language: JavaScript (javascript)

However, the following example returns null because the radius argument isn’t passed into the create() method:

let c2 = Circle.create(); console.log(c2); // nullCode language: JavaScript (javascript)

Check if a value is null

To check if a value is null , you use the strict equality operator === like this:

value === nullCode language: JavaScript (javascript)
const rect = null; const square = < dimension: 10 >; console.log(rect === null); // true console.log(square === null); // falseCode language: JavaScript (javascript)

The rect === null evaluates to true because the rect variable is assigned to a null value. On the other hand, the square === null evaluates to false because it’s assigned to an object.

To check if a value is not null , you use the strict inequality operator ( !== ):

value !== nullCode language: JavaScript (javascript)

JavaScript null features

JavaScript null has the following features.

1) null is falsy

Besides false , 0 , an empty string ( » ), undefined , NaN , null is a falsy value. It means that JavaScript will coerce null to false in conditionals. For example:

const square = null; if (square) < console.log('The square is not null'); > else < console.log('The square is null'); >Code language: JavaScript (javascript)
The square is nullCode language: JavaScript (javascript)

In this example, the square variable is null therefore the if statement evaluates it to false and executes the statement in the else clause.

2) typeof null is object

The typeof value returns the type of the value. For example:

console.log(typeof 10); // 'number'Code language: JavaScript (javascript)

Surprisingly, the typeof null returns ‘object’ :

console.log(typeof null); // 'object'Code language: JavaScript (javascript)

In JavaScript, null is a primitive value, not an object. It turns out that this is a historical bug from the first version of JavaScript that may never be fixed.

A common JavaScript null mistake

In JavaScript, you often call a function to get an object. And then you access the property of that object.

However, if the function returns null instead of an object, you’ll get a TypeError . For example:

let classList = document.querySelector('#save').classList;Code language: JavaScript (javascript)

In this example, we select an element with id save and access its classList property.

If the page doesn’t have any element with the id save , the document.querySelector(‘#save’) returns null . Hence, accessing the className property of the null value results in an error:

Uncaught TypeError: Cannot read property 'classList' of nullCode language: JavaScript (javascript)

The optional chaining operator returns undefined instead of throwing an error when you attempt to access a property of a null (or undefined ) value.

The following example uses the optional chaining operator that returns undefined instead of an error:

let classList = document.querySelector('#save')?.classList;Code language: JavaScript (javascript)

JavaScript null vs. undefined

Both null and undefined are primitive values.

The undefined is the value of an uninitialized vairable or object property.

For example, when you declare a variable without initializing a value, the variable evaluates to undefined :

let counter; console.log(counter); // undefinedCode language: JavaScript (javascript)

The null represents an intentional absence of an object while the undefined represents an unintentional absence of a value.

In other words, the null represents a missing object while the undefined represents an uninitialized variable.

The null and undefined are equal when you use the loose equality operator ( == ):

console.log(null == undefined); // trueCode language: JavaScript (javascript)

The strict equality operator === differentiates the null and undefined . For example:

console.log(null === undefined); // falseCode language: JavaScript (javascript)

Summary

  • Javascript null is a primitive type that has one value null.
  • JavaScript uses the null value to represent a missing object.
  • Use the strict equality operator ( === ) to check if a value is null .
  • The typeof null returns ‘object’ , which is historical bug in JavaScript that may never be fixed.
  • Use the optional chaining operator ( ?. ) to access the property of an object that may be null .

Источник

Checking null object in javascript

Last updated: Dec 21, 2022
Reading time · 5 min

banner

# Table of Contents

# Check if all Object Properties are Null

To check if all of an object’s properties have a value of null :

  1. Use the Object.values() method to get an array of the object’s values.
  2. Use the Array.every() method to iterate over the array.
  3. Check if each value is equal to null .
  4. The every() method will return true if all values are null .
Copied!
const obj = a: null, b: null>; const isNullish = Object.values(obj).every(value => if (value === null) return true; > return false; >); console.log(isNullish); // 👉️ true

NOTE: if you just need to check if an object is empty, use the Object.keys() method.

Copied!
const obj = a: null, b: null>; if (Object.keys(obj).length === 0) console.log('The object is empty'); > else console.log('The object is NOT empty'); >

We used the Object.values() method to get an array of the object’s values.

Copied!
const obj = a: null, b: null>; // 👇️ [null, null] console.log(Object.values(obj));

The function we passed to the Array.every method gets called with each value in the array.

If the value is equal to null , the function returns true , otherwise false is returned.

The Array.every() method will return true only if the callback function returns true for all values in the array.

If the every() method returns true , then all of the object’s values are null .

You can also check if the object’s values are set to null , undefined or empty string, or any other value that your use case requires.

Copied!
const obj = a: null, b: undefined, c: ''>; const isNullUndefEmptyStr = Object.values(obj).every(value => // 👇️ check for multiple conditions if (value === null || value === undefined || value === '') return true; > return false; >); console.log(isNullUndefEmptyStr); // 👉️ true

The code sample checks if each value in the object is null , undefined or empty string .

We used the || (OR) operator, which means that only 1 of the 3 conditions has to be satisfied for the if block to run.

# Check if all Object properties are True

The same approach can be used if you need to check if all object properties are True .

Copied!
const obj = first: true, second: true, >; const allTrue = Object.values(obj).every( value => value === true ); console.log(allTrue); // 👉️ true

The allTrue variable stores a true value if all properties in the object are true and false otherwise.

# Check if all Object properties are Falsy

You can also check if all values in an object are falsy .

The falsy values in JavaScript are: null , undefined , false , 0 , «» (empty string), NaN (not a number).

All other values in the language are truthy.

Copied!
const obj = a: null, b: undefined, c: '', d: 0, e: false>; const isFalsy = Object.values(obj).every(value => if (!value) return true; > return false; >); console.log(isFalsy); // 👉️ true

All of the values in the object are falsy, so the test function passes on all iterations.

We used the logical NOT (!) operator to convert each value to a boolean and flip the result.

Here are some examples of using the logical NOT operator.

Copied!
console.log(!true); // 👉️ false console.log(!false); // 👉️ true console.log(!'hello'); // 👉️ false console.log(!''); // 👉️ true console.log(!null); // 👉️ true

The operator converts each value to its boolean representation and flips it.

If all of the values in the object are falsy, the test function we passed to the every() method would return true on all iterations.

# Check if all values in an object are Truthy in JavaScript

To check if all values in an object are truthy:

  1. Use Object.values() to get an array of the object’s values.
  2. Use the Array.every() method to iterate over the array.
  3. Return each value straight away.
Copied!
const obj = first: 'bobbyhadz.com', second: true, third: 1, >; const allTruthy = Object.values(obj).every(value => value); console.log(allTruthy); // 👉️ true

All of the values in the object are truthy, so the test function passes on all iterations because we return each value directly.

An alternative approach is to use a shorthand method, where we leverage the Boolean() constructor.

Copied!
const obj = first: 'bobbyhadz.com', second: true, third: 1, >; const areTruthyShort = Object.values(obj).every(Boolean); console.log(areTruthyShort); // 👉️ true

The Boolean() constructor converts each element in the array to its boolean representation and returns the result.

This code sample achieves the same result as the previous one, however, is a little more concise and implicit.

# Set all Values in an Object to Null in JavaScript

To set all values in an object to null:

  1. Use the Object.keys() method to get an array of the object’s keys.
  2. Use the forEach() method to iterate over the array.
  3. Set each value in the object to null .
Copied!
const obj = name: 'Bobby', age: 30, country: 'Chile', >; Object.keys(obj).forEach(key => obj[key] = null; >); // 👇️ console.log(obj);

We used the Object.keys method to get an array of the object’s keys.

Copied!
const obj = name: 'Bobby', age: 30, country: 'Chile', >; // 👇️ [ 'name', 'age', 'country' ] console.log(Object.keys(obj));

The next step is to use the Array.forEach method to iterate over the array.

On each iteration, we set the value of the current key of null .

After the last iteration, all of the values in the object will be set to null .

An alternative approach is to not mutate the object, but create a new object using the Array.reduce method.

# Set all Values in an Object to Null using reduce()

This is a three-step process:

  1. Use the Object.keys() method to get an array of the object’s keys.
  2. Use the Array.reduce() method to iterate over the array.
  3. Set each object value to null and return the result.
Copied!
const obj = name: 'Bobby', age: 30, country: 'Chile', >; const newObj = Object.keys(obj).reduce((accumulator, key) => return . accumulator, [key]: null>; >, >); // 👇️ console.log(newObj);

The function we passed to the Array.reduce() method gets called for each element in the keys array.

We set the initial value for the accumulator variable to an empty object.

On each iteration, we use the spread syntax (. ) to unpack the key-value pairs of the accumulated object into a new object, setting the current property to null .

# Set all Values in an Object to Null using Object.fromEntries()

This is a three-step process:

  1. Use the Object.keys() method to get an array of the object’s keys.
  2. Use the Array.map() method to get an array of key-value pairs.
  3. Use the Object.fromEntries() method to create an object with null values from the array.
Copied!
const obj = name: 'Bobby', age: 30, country: 'Chile', >; const newObj = Object.fromEntries(Object.keys(obj).map(key => [key, null])); // 👇️ console.log(newObj);

We called the Array.map() method on the array of keys.

The function we passed to the Array.map() method gets called with each element in the array.

On each iteration, we return an array containing the key and a null value.

Copied!
const obj = name: 'Bobby', age: 30, country: 'Chile', >; // 👇️ [ [ 'name', null ], [ 'age', null ], [ 'country', null ] ] console.log(Object.keys(obj).map(key => [key, null]));

The map() method returns a new array containing the values returned from the callback function.

The last step is to use the Object.fromEntries() method to create an object from the array of key-value pairs.

The Object.fromEntries transforms a list of key-value pairs into an object.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Python requests read file
Оцените статью