0
const obj = {
  id: 1,
  nested: null
}

obj.nested = obj;

console.log(obj)

Why this code is created nested obj inside nested key and keeps going on? I know that array and object is pass By Reference in javascript.

  • Well, `obj.nested` points to `obj`. And `obj.nested` points to `obj`. And `obj.nested` points to `obj`… You get the idea… – deceze Apr 25 '22 at 08:06
  • 1
    _"Why this code is created..."_ - Ask the author of that snippet. – Andreas Apr 25 '22 at 08:07
  • @Andreas I m the author of this snippet. I was doing some sort of programming and suddenly got bumped on this on my console :). – Moiz Ratlamwala Apr 25 '22 at 08:09
  • @SomShekharMukherjee you can add your answer to one of the existing questions if it's relevant there and not already answered. – freedomn-m Apr 25 '22 at 08:29
  • @freedomn-m Those questions are more on "Can" and this one was on "Why/How" – Som Shekhar Mukherjee Apr 25 '22 at 08:36
  • 1
    It points to itself - [a circular reference](https://en.wikipedia.org/wiki/Circular_reference). It does not create nested objects. It is always the same object. – Lain Apr 25 '22 at 08:36
  • @SomShekharMukherjee hence the "if relevant there" - you can vote for reopen on this question if you think it's different. – freedomn-m Apr 25 '22 at 08:40

0 Answers0