My understanding is that when you want to create a new object in Javascript, it's best to use JSON notation:
let foo1 = {};
let foo2 = {};
foo1 = `Hola ${user}`;
foo2.name = user;
So I have been surprised when, when reviewing code that has been bequeathed to me, I have found something like:
let httpResponse = null;
if (condition) {
httpResponse = 'Error processing request'
} else {
httpResponse = JSON.parse(data)
}
Why have my peers put null to initialize the object? Are there differences between both ways?
I go by parts:
This code is wrong . It works, but it does things that are not necessary:
As you can see, you first assign an empty object to
foo1
, but then you assign astring
, so the initial object is lost. In the case of foo2 it makes sense because you are adding properties to the already created object.The same goes for this other code:
Setting it to null is unnecessary because you have a
if-else
. If you had aif-else-if
, there would be a chance that nothing would be assignedFinally, let's assume that your code really is more complex than what you have put in the example and it needs a default value. Initializing to
null
may make sense if your checks are strict, but remember that itnull == undefined
is alwaystrue
. In fact, as long as you're not working with numbers, it's more comfortable to do something likewhere
variable
it is considered false if it is null, undefined or an empty string. An object (empty or not), including an array (empty or not) or a string with length greater than 0 is considered true . With numbers, 0 is false and any other value, positive or not, is true.So what is the difference between having an empty object and having null/undefined? Well, what we have seen with foo2, you can add the properties you need to an empty object, while you cannot add the properties to a null/indefined object, since it would cause the well-known Cannot set property ... of null error :