Lets explain the Code:
Step 1: Object Declaration
What happens here:
- You are creating an object
xwith two properties: - Property
ais explicitly assignedundefined. - Property
bis explicitly assignednull.
Quick property breakdown:
undefined- Represents the absence of a value.
- Often appears when a variable or object property has been declared but not assigned a value.
null- Represents the intentional absence of any object value.
- It is explicitly set by the developer to indicate "no value" or "empty."
Step 2: JSON.stringify(x)
What is JSON.stringify?
It is a built-in JavaScript method that converts a JavaScript object or value into a JSON string.
Key Rule:
When you convert an object to JSON:
- Properties with
undefinedare excluded from the final string. - Properties with
nullare included.
According to the JSON specification:
- JSON supports:
- Numbers
- Strings
- Booleans
- Arrays
- Objects
- null
- JSON does not support
undefinedas a valid value.
How JSON.stringify Works in This Case:
Original object:
After applying JSON.stringify(x):
Explanation:
-
Property
ais ignored because its value isundefined(not serializable in JSON). - Property
bis included becausenullis a valid JSON value.
✔ Final Answer:
B) {"b":null}
This question appeared in the Epam 2nd round of interview, testing the candidate’s knowledge of Json data type convert object into Json vise-versa in JavaScript.
Why Does This Happen?
- JSON.stringify skips:
undefinedvalues- Function properties
- Symbol properties
JSON.stringify includes:
- Numbers
- Strings
- Booleans
- Objects
- Arrays
- null
Key Notes:
| Value Type | Behavior in JSON.stringify |
|---|---|
undefined | Skipped |
null | Included |
| Function | Skipped |
| Symbol | Skipped |
Example Extension:
The undefined property is skipped, but null, numbers, and strings are included.
Final Summary:
| Step | Action | Result |
|---|---|---|
| 1 | Declare object with undefined and null | Object created |
| 2 | Apply JSON.stringify | undefined skipped |
| 3 | Print JSON string | {"b":null} |
Key Takeaways:
undefined is not valid in JSON and is excluded from the JSON string.null is valid in JSON and is included.JSON.stringify creates cleaner JSON by removing non-serializable values automatically.
