G
G
GunAlv2021-01-27 18:37:52
JavaScript
GunAlv, 2021-01-27 18:37:52

Is empty object in state instead of null bad practice?

For example, in a container component, you can specify the state as

state = {
   someValue: {} // null
}


What is the difference in approaches? If I set an empty object, I can use its fields without having to check for their existence: this.state.someValue.test. In case of null there will be a natural error

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2021-01-27
@GunAlv

Doesn't affect performance. Affects the one who later (perhaps you yourself) will then catch bugs.
undefined - means that the variable is not defined.
null - means "empty".
Accordingly, in the console, when I see undefined, then I will go first of all to check the input parameters of the component / function / etc.
If I see null, then I will go first of all to check overrides / entries.
If you leave an empty object, then it's a little more complicated.
If you need to FIRST get the data, and only then access the object, then it will not be possible to check for an empty object, because the if statement does not compare fields and methods, but checks whether two variables refer to the same object.

const obj = {};

const obj2 = {};

console.log( obj === obj2 ) // false

if( obj === {} ) // false

Personally, I usually set the default value to null if no other value can be set. For example, when there is a function that returns a random number between max and min, it is convenient to make the input min parameter 0 by default.
But if you don’t have any special logic, or the field is reactively tied to the interface, then an empty object is also normal.

A
Anton Anton, 2021-01-27
@Fragster

Is empty object in state instead of null bad practice?

More often yes. You can use undefined instead of null.
And for properties there is Optional_chaining

K
Kirill Makarov, 2021-01-28
@kirbi1996

Run typescript, it will tell you where is good and where is bad practice

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question