Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an undefined key of an object to undefined in JavaScript

If I open my JavaScript console (F12 on Chrome) and define a variable var x = {}; and then type x in the console it shows me an empty object like this: {}. So far so good.

If try to see x.a the console will give me undefined, and if I explicitly test x.a === undefined it gives true. So far so good.

Everything is telling me that the value of x.a is undefined.

So, since its value is undefined, I now execute a command that I was expecting to do absolutely nothing: x.a = undefined;. I thought this shouldn't change anything.

But now if I put x in the console, it shows {a: undefined} instead of {}. This is an evidence that something changed...

1. What is happening here?

2. Is there any situation in which this would make a difference?

3. If yes, how can I make that object go back to its initial state?

Note: of course, for question 3, re-assigning to a new {} is obviously not an option, since it would no longer === to the previous value.

like image 738
Pedro A Avatar asked Oct 24 '25 03:10

Pedro A


1 Answers

1. What is happening here?

At first you are accessing a non-existing property. That will always return undefined as defined in the language specification.

But a property can also exist and have the value undefined, which is what you are getting when doing

x.a = undefined;

This creates the property a on x and assigns the value undefined to it.

2. Is there any situation in which this would make a difference?

Testing the existence of the property would result in false in the first case and true in the second case.

var x = {};
console.log('a exists', 'a' in x);

x.a = undefined;
console.log('a exists', 'a' in x);

The value of the property is irrelevant when testing for existence.

Similarly, getting all properties of an object would yield different results:

var x = {};
console.log(Object.keys(x));

x.a = undefined;
console.log(Object.keys(x));

3. If yes, how can I make that object go back to its initial state?

You can delete properties using the delete operator:

delete x.a;
like image 179
Felix Kling Avatar answered Oct 25 '25 19:10

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!