JavaScript: 6 practices to be aware of

JS can be tricky — here are a few things to be aware of, to not mess up your code

Yeah, we all know JavaScript can be pretty strange. But most of us, including me, love it. Even with it’s weird concepts. And so that we all can continue to love JavaScript & not bother with stupid things in the future, I’ve written this article to clear up a few of them.

Oh no… it’s retarded!

1). Did you know that you can calculate with strings in JavaScript?

That shouldn’t look unusual for you at first, should it?

11 + 1 // 12

'11' + 1; // 111

11 – 1; // 10

But here comes the magic:

'11' — 1 // 10

Yes, JavaScript automatically converts strings into numbers, so you could make the 1 a string here to. This would lead to the same result.

The proof is that if you have two strings containing letters and want to subtract them from each other, JavaScript will only output NaN, i.e. “Not A Number”.

Quintessence: Always make sure that you are working with the correct data type

2). Blocking the event loop

Let’s start this with a simple question. Which name will be printed out through the console.log?

let name = ‘Max’

setTimeout(function() {

name = ‘Tom’ }, 1000) console.log(name)

Correct. Max will be printed. The setTimeout won’t stop the whole JavaScript from being executed, because JavaScript recognizes a function, the console.log, even when it is after the setTimeout in the code.

The function will be executed first, then JS is going to run that setTimeout.

Here is a more complex example:

let start = Date.now() let doWork = () => { console.log(‘doWork started’) for (let i = 0; i < 999999999; i++) {}

console.log(‘doWork done after’, Date.now() — start)

} let clickme = () => {

alert(‘clicked after’, Date.now() — start)

} doWork() setTimeout(function() {

console.log(‘setTimeout done after’, Date.now() — start)

}, 1000) doWork()

Make sure to run this in your browser. Here are the results, the times can differ

doWork started

doWork done after 854

doWork started

doWork done after 1429

setTimeout done after 1858

What we can see is, that once again the setTimeout will be delayed. But did you also notice that “clickme” function in the code? Create a simple HTML button to executed when ever you click on it, and you will see that also the simple alert will be delayed, as long the doWork function are executed.

And again, the setTimeout will be delayed. But this time not only from the doWork functions, but also from the clickme function.

What do we learn from this? Always keep in mind how the event loop in JS works. This can prevent a lot problems with HTTP Requests for example & make sure to never block the event loop, when the user should be able to execute a function, as in our example, through a button. Just imagine the button click should open up a dropdown. This delay would kill your UX.

3). Strange scoping rules

In JavaScript we have to scopes. The global and the local scope. Just two one, but they can lead to much confusion.

When we define a variable inside of a function, it will be only available in the local scope. That is what most of us thought. But this is not always true in JavaScript.

function hello() {

message = ‘Hello!’

} console.log(message) // message is not defined hello()

But once the function is executed, the variable is available globally. This works even if the function is called in code before it is even defined.

(Which is called hoisting, but does not work for Arrow functions, see more: Arrow vs. Regular Functions)

hello() console.log(message) // Hello function hello() {

message = ‘Hello!’

}

4). 0.1 + 0.2 is 0.3? Well yes, but actually no.

And to be honest, this is not just a problem in JavaScript. If you perform the same operation in Python, for example, the same result will await you.

0.1 + 0.2 // 0.30000000000000004

But it is not only here that calculating with JS is not quite exact:

2.3 * 100 // 229.99999999999997

5). Clean up an Array in JavaScript? There are a few ways, but just 2 proper ways

For this section, I refer very much to an interesting study of performance, from 5 different ways to empty an array in JS.

http://jsben.ch/hyj65

As you can see from this experiment, this is the fastest way:

var arr1 = [“a”, “b”, “c”, “d”, “e”, “f”];

var arr2 = arr1;

arr1 = [];

So theoretically you only need to reinitialize the array to empty it? Yes.

But is this always the best way? No.

Because of what happens here:

var arr1 = [“a”, “b”, “c”, “d”, “e”, “f”];

var arr2 = arr1; // Reference arr1 by another variable

arr1 = [];

console.log(arr2); // [“a”, “b”, “c”, “d”, “e”, “f”]

As we see, the actual array is emptied, but arr2 still contains it’s complete contents.

But according to our experiment there is a second way, which is almost as fast: Just set the length of the Array to 0.

var arr1 = [“a”, “b”, “c”, “d”, “e”, “f”];

var arr2 = arr1;

arr1.length = 0;

console.log(arr2); // [ ]

6). Dangerous inaccuracy when passing parameters

Let’s create a simple function to add 2 values:

function add(a, b) {

return a + b;

} add(2, 2); // 4 // one param missing — won’t work

add(2); // NaN // one param too much — doesn’t care

add(2, 2, 10); // 4

Logically, everything works if we pass exactly two parameters. But what happens if we pass one too many, or even one too few? Different things.

If we hand over too few, it will lead to an error. If we hand over too many, all those that are too much are simply ignored. However, JavaScript does not give an exact warning in both cases.

Workarounds

First, you could just use default values for your parameters, which will be applied if nothing else is passed for the parameter.

function add(a, b = 2) {

return a + b;

} add(2); // 4

add(2, 3); // 5

Another option would be to turn the parameters into one array, that contains everything, what is passed into the function. Yes, as you can see you don’t need to define in the function itself, what it can expect as parameters.

function paramArray() {

return Array.from(arguments);

} paramArray(2, 2, 2); // [2, 2, 2]

That’s it so far

This article is constantly being expanded so that we finally have an ultimate list of the blunders in JavaScript.

So feel free to leave your feedback & add anything in the comments :)

Thank you for reading!

Hi! Thank you very for reading my blog, my name is Louis and I am a 18 years old student from Germany. I am in love with Webdevelopment, both backend and frontend. My favorite technologies are React, Vue, React Native and Node.js.

Make sure to follow me for more content related to those, and feel free to have a look on my IG’s @louis.jsx & @codingcultureshop

Have a nice day & feel free to leave me your feedback :)