I have a code like below.
var t = [1, 2];
t[2] = t;
This creates a circular array. What is the algorithm applied to create this circular array in javascript.
There's no algorithm involved. It's just that your array refers to itself. When a variable or property refers to an object (arrays are objects), what's held in the variable is an object reference, which is a value that tells the JavaScript engine where that object is elsewhere in memory. You can think of it as a number that uniquely identifies a memory location where the object is. (That isn't what it is, but it's a handy way to think of it.)
Let's look at the code. You start with:
var t = [1, 2];
That creates an array and stores an object reference for it in t
. That creates something somewhat like this in memory (various details omitted for clarity):
+−−−−−−−−−−−−−−−+ t:{Ref18465}−−−−−>| (array) | +−−−−−−−−−−−−−−−+ | length: 2 | | 0: 1 | | 1: 2 | +−−−−−−−−−−−−−−−+
The Ref18465
I've shown is a stand-in for the object reference, which we never directly see in code. We have an array, and a variable containing an object reference saying where the array is.
Then your code does this:
t[2] = t;
That adds a new element to the array containing the object reference of the array, making it refer to itself:
+−−−−−−−−−−−−−−−−−−−−−−+ | | \ +−−−−−−−−−−−−−−−+ | t:{Ref18465}−−−+−>| (array) | | +−−−−−−−−−−−−−−−+ | | length: 3 | | | 0: 1 | | | 1: 2 | | | 2: {Ref18465} |>−/ +−−−−−−−−−−−−−−−+
Now, both t
and t[2]
contain the object reference to the array. As you say, the array refers to itself. There's no particular algorithm involved, it's just a circular data structure.