40
Advanced JavaScript Series - Part 1: Behind the scenes (JavaScript Engine, ATS, Hidden Classes, Garbage Collection)
JavaScript is a single-threaded, synchronous programming language. It means that when a script is run, the JS engine runs the code line by line, beginning at the top and working its way down.







function cupcake(frosting,sprinkles) {
this.frosting = frosting;
this.sprinkles = sprinkles;
}

1 function Point(x,y) {
2 this.x = x;
3 this.y = y;
4 }
5
7 var obj1 = new Point(1,2);
8 var obj2 = new Point(3,4);
9
10 obj1.a = 5;
11 obj1.b = 10;
12
13 obj2.b = 10;
14 obj2.a = 5;
Up until line 9, obj1 and obj2 shared the same hidden class. However, since properties a and b were added in opposite orders, obj1 and obj2 end up with different hidden classes.
1 function Point(x,y) {
2 this.x = x;
3 this.y = y;
4 }
5
7 var obj1 = new Point(1,2);
8 var obj2 = new Point(3,4);
9
10 obj1.a = 5;
11 obj2.a = 5;
12
13 obj1.b = 10;
14 obj2.b = 10;
JS collects garbage with a mark and sweep method.
Credits- Andrei Neagoie
In this example, a memory leak is created. By changing the value of person
, we leave the previous value in the memory heap thus causing a leak.
Best practice against memory leaks are to avoid global instantiation, instead we should instantiate only inside functions, where required.
Appendix-
40