1

I was just playing with JS and I came across this strange behavior.

Code is as follows

let a = {
    "b" : 1,
    "a" : function(){
    return 1;
  }
}

let b = {
    "b" : 2,
    "a" : ()=>{
    return 2;
  }
}


let x = JSON.stringify(a);
console.log("For a ",JSON.parse(x));

x = JSON.stringify(b);
console.log("For b ",JSON.parse(x));

As you can see the object containing the value as a function gets removed automatically after we parse the stringified object.

I was wondering why and how it happened ??

Jeel Patel
  • 43
  • 6
  • You cant stringify a function, it will be lost in the process, there is no such thing as a function in the JSON spec – Lk77 Aug 22 '22 at 14:49
  • 2
    It get's removed by stringifying it. This is not strange at all if you consider that JSON is a text format to store data, not instances of objects. –  Aug 22 '22 at 14:51

0 Answers0