2
var arr1 = [1, 2, 3, undefined, 4, 5];
var arr2 = JSON.parse(JSON.stringify(arr1));
console.log(arr2);

Output of the above code will be....

[1, 2, 3, null, 4, 5]

Why it converts it's 4th value from "undefined" to "null"?

3
  • ECMA-404 (no joke, the standard of JSON) does not know undefined. Commented Aug 17, 2020 at 13:24
  • stackoverflow.com/questions/13796751/json-undefined-value-type Commented Aug 17, 2020 at 13:24
  • Undefined is not valid json, so JSON.parse converts it to null. Then when converted back, since null is valid JS, it keeps the null Commented Aug 17, 2020 at 13:25

1 Answer 1

2

Because undefined is a Javascript type. There is no undefined in JSON.

According to the spec:

JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.