Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow when writing JavaScript code.

Rounding Number to N Decimal Places

We can round numbers with the toFixed method.

It takes the number of decimal places to round to as the argument.

For example, we can write:

let num = 2.575949004696;
num = num.toFixed(3);

It returns a string with the rounded number.

So we get “2.576” as the new value of num .

Floating-Point Problems

We should be aware that adding floating numbers may not give the results we expect.

For example, if we have:

0.1 + 0.2 === 0.3

Then we get false .

This is because floating-point numbers are 64-bit binary numbers.

The conversion will give us discrepancies.

To fix this, we use the toFixed or toPrecision methods.

Check the Properties of an Object When using a for-in Loop

To check the properties of an object with the hasOwnProperty method.

For example, we can write:

for (let name in object) {
  if (object.hasOwnProperty(name)) {
    // ...
  }
}

We check that the property is in the object itself rather than its prototypes with hasOwnProperty .

#programming #web-development #javascript #technology #software-development

JavaScript Tips — Rounding and JSON
1.20 GEEK