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
.
Comma Operator
The comma operator always returns the last item in the list.
So if we have:
const a = (100, 99);
Then a
is 99.
Cache Variables that Need Calculation or Querying
To speed up our app, we should cache variables whenever we can.
For example, we write:
const navRight = document.querySelector('#right');
const navLeft = document.querySelector('#left');
const navUp = document.querySelector('#up');
const navDown = document.querySelector('#down');
Then we won’t use the variables anywhere instead of querying the DOM all the time.
Verify the Argument Before Passing it to isFinite()
isFinite
lets us check if an expression returns a finite number.
For example, we can write:
isFinite("foo")
it returns false
.
If we have:
isFinite(10)
it returns true
.
Serialization and Deserialization with JSON
We can use the JSON
object to serialize and deserialize JSON.
To convert objects to JSON, we use JSON.stringify
.
To parse JSON strings into objects, we use JSON.parse
.
We can use JSON.stringify
by writing:
const str = JSON.stringify(obj)
It returns the stringified JSON object.
Also, we can pass in additional arguments to make the string more readable:
const str = JSON.stringify(obj, undefined, 2);
The 3rd argument has the number of spaces to indent.
To parse a JSON string to an object, we write:
const obj = JSON.parse(str)
where str
is the JSON string.
Avoid the use of eval() or the Function Constructor
We should avoid eval
and the Function
constructor since they both run code from strings.
This is security risk since we can pass malicious strings into it.
Code in strings can’t be optimized and they’re hard to debug.
Avoid Using with()
with
should never be used since the scope is confusion.
Variables can be inserted at the global scope, which is also not good.
If 2 variables have the same name in a with
statement, it can overwrite the value.
Conclusion
There’re things in JavaScript we should avoid.
We can round numbers and manipulate JSON with the standard library.