Russell Ormes
Russell Ormes

Reputation: 533

Why can't I set object property to empty string in JavaScript?

I want to pass the values from my request body into a paramsDict object where I have defined constraint to test the parameters against. I don't require that all possible parameters are sent with every request and also, if a value is deleted on the client, it can be sent as an empty string.

So we pass the values to the dictionary like so

for ( p in paramsDict ) {
   if ( container[p] ) {
      paramsDict[p].value = container[p];
   }
  }

where container is set to req.body (in node.js express).

In the case where container[p] = "" the property paramsDict[p].value never gets set, i.e typeof paramsDict[p].value returns "undefined" (note: it does not exist on the object before I attempt to assign it here). This means adding an extra check which I would rather not have to:

if (typeof container[p] == "string" && container[p].length == 0){
  paramsDict[p].value = "";
}

Investigating I see that paramsDict[p].value = "" and paramsDict[p].value = false both set the property to the empty string and false respectively (I include false because the empty string is falsey in JS).

typeof container[p] returns "string" when the value is the empty string so I am very surprised that is does not assign the empty string as the value.

Is this a decision that has been made for this implementation of JS or is it a bug?

Upvotes: 0

Views: 1556

Answers (2)

MatthewG
MatthewG

Reputation: 9303

Your check for the property [p] will return false even in the cases you care about (empty string or false). Instead of if (container[p]), you should use if (container.hasOwnProperty(p)).

Upvotes: 2

JMM
JMM

Reputation: 26807

You answered your own question: empty string is falsy, so this will evaluate to false when container[p] === '':

if ( container[p] ) {

So, assignment to paramsDict won't happen.

Upvotes: 1

Related Questions