3

On the server, I serialize my objects and sometimes, some properties are null. On the page, when I parse the string, the null properties are deserialized correctly and in my javascript, I test to see if the properties for which there might be a null are indeed null or not before working with them; like this:

if (TheObject.TheProp && TheObject.TheProp.length) {...}

It doesn't crash and it works. My question is this: should I, on the server, populate every property with something (ie. "" for strings and 0 for numbers) because it's considered good practice or is it ok to have null properties on the page?

Thanks for your suggestions.

2
  • 1
    If a property is null then it's most semantical to keep it null. JSON has a null value after all; I don't see what advantage an empty string has. Commented Mar 17, 2012 at 16:20
  • Well "" is two characters shorter than null, but in my opinion there's a significant semantic difference between an empty string and null; at least, there certainly can be. Commented Mar 17, 2012 at 16:20

2 Answers 2

1

In JavaScript null is a value just like "" and 0. A value is undefined if you have defined it, but not assigned a value, but even that is fine. undefined will never occur in a JSON data structure though.

Just make sure you handle the nulls correctly and you should be fine.

Sign up to request clarification or add additional context in comments.

Comments

1

It's really up to you. If there's a difference between an empty value "" and an non-existent value null, then you would want to preserve null as the marker for the non-existent value and "" as the market for an empty value.

If there's no difference in your app between the two, then you can indicate an empty string value with either "" or null. In some cases, it's' simpler to use "" because it is a string so you can then treat all your values as strings, but which you use is purely up to your own coding convenience.

There is no single answer which is more right.

1 Comment

ok, thanks: I'll leave my objects as is and continue to check for null via the (Object.Property)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.