Category: JavaScript

JavaScript: Recursive and iterative object deletion

The use of object is quite important in javascript especially in complicated web applications. Although JavaScript engines clean up after themselves once the variable is no longer referenced, but from time to time there might be needs to manually “dispose” objects to free up memories or for security reason. In JavaScript, this can be achieved by the delete keyword.

So a very simiple way of doing this is just iterating through all child objects and do the work:

var person = {firstName:"Leon",lastName:"Zhou",age:"28",sex:"male"};
for (var obj in person) delete person[obj];
delete person;

However, what if you want to delete children objects that are more than 1 level deep? This is usually done in a recursive way:

function dispose(obj) {
    for (var o in obj) if (isNaN(parseInt(o))) dispose(obj[o]);
    delete obj;
}

var person = { name: { first: "Leon", Last: "Zhou" }, age: "28" };
dispose(person);
delete person;

Note that in the recursive function dispose, I had to check if o is an integer. This is to prevent the function going into infinite recursion because when obj is a single letter, the first var o in obj will always be “0”, and obj[o] will always return obj itself.

JavaScript: Creating inline DOM objects

Honestly, it’s been a long time since I touch any javascripts but they still remain fun and powerful for me. Recently I came across a situation that I need to create some DOM objects using javascript. After a little search, I found out that it’s exactly how JSON objects are created:

var myObj =
[{
  title: 'My Object',
  dataList:
  [
    {name: 'data 1', value: 'value 1'},
    {name: 'data 2', value: 'value  2'}
  ]
}]