Reputation: 1943
I am asking this question after reading this question.
NOTE I know the difference between null
and undefined
.
Let me show you an example,
let a = {};
console.log(a.test); // undefined
Now what if I add a property with test1: undefined
a.test1 = undefined;
console.log(test1); // undefined
console.log(a); // { test1: undefined }
Now tell me what is undefined
. Is it a value or something
Upvotes: 0
Views: 113
Reputation: 96
undefined is a falsy value in Javascript. If a variable is not assigned with some value, then JS automatically assigne a value of undefined.
let a = {};
In this case, the object is blank. And accessing any value of a
would give undefined.
However, if some values are assigned to a
, in your case
a.test1 = undefined;
In this, a has some values, so a.test1 will not give you undefined that was assigned by default to the variable as you have already assigned some values to it. And on accessing it, you will get the value assigned i.e undefined
Upvotes: 0
Reputation: 2587
It is a one of the javascript primitive types.
Javascript will assign undefined
to any variable or object's property which is not declared.
undefined
is one of the falsy values in javascript like null
.
let a = {};
console.log(a.test); // undefined
In the above snippet test
property is undefined cause javascript assigns undefined to variables or object's properties which declared but not assigned any value.
a.test1 = undefined;
console.log(test1); // undefined
console.log(a); // { test1: undefined }
In the above snippet, you are specifically assigning undefined to test1
property of a
. If you don't assign any value then it will contain undefined by default JS behavior as shown below
a.test1;
console.log(a); // { test1: undefined }
One more interesting feature of undefined is with JSON. JSON.stringify will ignore all properties of object which are undefined.
let obj = {a:1, b:undefined};
console.log(JSON.stringify(obj)); // {a:1}
For more about primitive types undefined
Upvotes: 3