I have a case where I have a dictionary object and a value with no key.

The object can have the system values and then a user value. I have to store that value.

I could use a reserved word or I could use null.

userValue = "enabled";
data = {version: 10, date: 10101010};
data.name = "Charleen";

// reserved word
data["MyReservedWordIHopeNoOneStumblesUpon"] = userValue;

// or use null
data[null] = userValues;

If I use a reserved word a user may stumble upon it one day (highly unlikely). That reserved word would also be stored or saved and may not make sense.

I could also use null or undefined as keys. But if I was iterating through the object and I encountered null or undefined they could be bugs that I dismissed as coming from user values.

The code is not that complicated in that I could easily debug it and I could check for reserved words or null.

Have you ever used null or undefined as keys and is there any pros or cons or recommendations to doing so?

Note: Typescript gives a warning:

Type 'null' cannot be used as an index

But it works in ES6.


Dictionary keys in JavaScript are always converted to strings, so null just becomes the string "null". This is certainly not better than MyReservedWordIHopeNoOneStumblesUpon, but neither is really ideal.

If you are able to use Map, it would solve the problem, since Map allows objects as keys.

But in any case, such "special case" values (aka "sentinel values") tend to be a bad idea. You could instead have an object which hold the user value in one property and the dictionary as another.


How about using an object? Their whole purpose is information hiding. In JavaScript simply create some locally scoped variables in a function and return a nested scope... TypeScript will have something similar.

 function does_stuff_returns_object(arg)
     var my_private_data = { ...whatever...};
     return { data: "xyz"
            , action: function() {... my_private_data.something ... }

If you are not using an object, then do not hide the key. Why? Because you are using a Data-Structure and nothing is hidden so do not hide it. Make it very clear what it is. If the user changes it, they are responsible for the consequences.


The most direct solution would be to use a Symbol. Javascript introduced these in ES6 for specifically this type of issue where you want to add data that only you have access to.

const data = {};
const userValues = {hello: "world"};

const userValueSymbol = Symbol('userValues');
data[userValueSymbol] = userValues;

console.log(data[Symbol('userValues')]);  // undefined
console.log(data[userValueSymbol]);  // {hello: "world"}

Just keep your symbol in an unaccessible location and nobody without this symbol can access your data, much like a key for a lock.

Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.