VDOM and recursion

The html document can be parsed to a kind of hierarchy, which can be expressed as a tree.

What I’m gonna write in this post is just my image of the virtual DOM in browser.

When the browser load the html document, the html element is going to be interpreted into DOM obj. It seems like object:

vdom = {
this.name = "div"
this.attribute = {/*some attributes like id, class, name*/}
this.children = [/*another vdom if it has*/]
}

The code above is just one example of vdom.

Once htmlElement are interpreted to VDOM by browser, browser could manipulate the VDOM. That way browser manipulate VDOM in its memory and don’t need to access DOM directly.

It makes it faster and easier to consume the code in memory, rather than direct access to the dom.

I can only come up with pros in using VDOM, but if you wanna save your memory, it might be better to use the dom instead.

However, basically, it would be fine to use VDOM, I think.

The next thing is browser compare the created vdom(oldNode) to the new dom(newNode).

In other words, only when there is a difference between old and new Node, browser trigger the change to update state.

On top of that, when newNode’s children’s number is less than that of old one, it can update and remove the corresponding old status.

The things supposed to be happen in a recursive way because its data is tree.

Here is the pseudocode:

// Base case
// declare the function to compare two VDOM
// first, check we check difference between newNode and oldNode
// If there is, update the corresponding place to new state(newNode status)
// go through the both(new and old node) children
// once it find change, update old to new state.
// Recursive case
// if both child state are different, call this function recursively to iterate both children like that way:
func(newNode.children[index].children, oldNode.children[index].children) until both doesn't have any children.

The thing in the above sentence is we call its function recursively until both node have not any children.

As you might see that in the javasctipt object, the browser can easily operate those tasks than plain code.

The code go through those steps:

  1. change html into JavaSctipt object
  2. to watch the current status on the web page
  3. if change happens on it, check its difference
  4. the actions is, remove, add, and replace
  5. change it every time it can find difference

One more thing, virtual DOM is mainly used in JS libraries and actually browser is dealing with DOM directly.

For the efficiency of the coding and rendering the web page, it is getting used by many nowadays.

The reference article: