Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Quick Tip – The Order Of JavaScript Operations Do Count

DZone's Guide to

Quick Tip – The Order Of JavaScript Operations Do Count

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

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');
  parentElement.appendChild(element);
  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;
  parentElement.appendChild(element);
}

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.

Summary

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.

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}