Over a million developers have joined DZone.

Quick Tip – The Order Of JavaScript Operations Do Count

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Continuing the quick JavaScript performance tips (tip1 and tip2) I wrote, here is another thing to consider when writing your JavaScript code. The order of your operations can decrease your performance. Sometimes all you have to do is think about what you are doing and then you might avoid pitfalls like in the next scenario.

The Scenario

Lets look at an example of adding a new div element to the Document Object Model (DOM):

function addDiv(parentElement, text) {
  var element = document.createElement('div');
  element.textContent = text;

The function will add a new div element to the parent element and then change its text. What’s the problem with that? We are doing a trivial thing. The problem is the order of the operations which can trigger two reflows, one for appending the child and the other for changing the text.

Suggested Solution

Lets change the previous code sample and avoid the problem:

function addDiv(parentElement, text) {
  var element = document.createElement('div');
  element.textContent = text;

Putting the appendChild function at the end solves the problem and might trigger only one reflow. All the changes to the div are being done in memory and not on a DOM element.


The order of operations do count when dealing with JavaScript and browsers. When you have a set of operations don’t write the code as is, test it and check that you are not falling into pitfalls like triggering reflows.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}