Here are Top 5 Best Practices for JavaScript you MUST ALWAYS FOLLOW
Tags: javascript, webdev, beginners
Published: 2019-09-25 13:56:27

JavaScript is one of the most flexible and lenient programming languages out there, compared to the likes of Java or C++ which have much stricter rules. This means that often we encounter unexpected behaviour, even when we are writing the same code that we have written and tested before. As programmers, we do *not* like anything unexpected *(except for of course, Math.random(). We all love Math.random()!)* and so we strive to minimise these 'wrong' ways of writing code, that may or may not work at any point in time.

This article is intended for audiences with limited experience of JavaScript, and limited understanding of the language. I will be regularly posting articles both for relatively new JavaScript programmers and more advanced articles for experienced programmers. If you code in JavaScript, you might want to follow me. 

##1) Avoid Global Scope wherever possible
It is from personal experience that I am telling you this - global scopes are ALWAYS a pain to work with. Generally, you bundle JavaScript files by putting them in an `html` file using the `<script>` tag. This means that it is as if all these files were written together inside one single file, unless you use modules or some next generation tool like Babel.
There are many examples, many of which are complex to understand the importance of, but I'll try my best for this simple scenario.
Imagine you wanted to store some data for a canvas sketch, and you do it like this:
```javascript
let canvasWidth = 5;
let canvasHeight = 67;
let canvasMousePos = { x: 9, y: 6 };
```
This could be fine, but then when you want to add more properties for your canvas, you will pollute the global namespace even more. We use `Object` literals for this purpose. It is generally bad practice to store ANY similar data in separate global namespaces, which is also very good for when you need to expand. The following code shows a better way, and shows also for when you might want to include two canvases with different properties in the future.
```javascript
let mycanvas = { width: 5, height: 67, mouse: { pos: { x: 9, y: 6 } } };
let myothercanvas = { author: 'John', width: 50, height: 107, mouse: { pos: { x: 9, y: 6, z: 89 } } };
```
If you were paying attention, you might suggest using an `Array` to store these two canvases to further remove pollution of the global scope, which is exactly what you should do. At a certain point, you might want to start solving these problems with Object Oriented Programming.

##2) Do not omit Semi Colons
A feature that many new and amateur developers love about JavaScript is the fact that in most cases, semicolons ( ; ) are optional and the code runs without them. This feature is known as Automatic Semicolon Insertion. However, using this feature is not recommended and you *should* include any due semicolons as this can result in unexpected behaviour. Semi colons are also crucial for better readability.

##3) JavaScript Array Methods
We store lists in arrays and generally this is so that at some point in our code we will iterate over them, or do some sequential manipulation of this data. Array methods are really useful here.
Imagine I have an array of `users` each of whom has a name and some other properties associated with it. If I wanted only the names of these users I could make a new array, loop over the original array and push items into this new array like the first snippet, or we could just use the `map` method on our array.
```javascript
    const users = [{ name: 'John', age: 87, post: 'high' }, { name: 'Doe', age: 43, post: 'low' }];
    const names = [];
    for(let i = 0; i < users.length; i++) {
        names.push(users[i].name);
    }
    // alternatively, in one line
    const names = users.map(user => user.name); //["John", "Doe"]
```
For a list of all array methods and their use cases, click [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)

##4) Reusing any piece of code? Make it a function
How often does it happen that you write some functionality but have to use it again at some other place? I guess very often is the answer for everyone. Whenever you see yourself reusing a piece of code, even if it is just two times, make it into a function. This will mean that if you want to change how that code works in the future (and trust me this will always happen), you will only need to change this in one place instead of 23 places inside 5 JavaScript files.


##5) Make your code concise wherever possible
JavaScript code allows flexibility in syntax. So much so that it is possible to make code blocks very concise by omitting redundant parts of the syntax, without breaking recommended patterns. For example the following omits curly braces where they are redundant.
```javascript
if (this.isHungry()) this.stroll()
else if (inPerception.length <= 2) this.stroll(() => this.inPerception > 2);
else {
	this.cohesion(inPerception, cohesionPriority / 100);
	const colliding = peerTree.retrieveFromRadius(pos.x, pos.y, r, this.isOfTypeSelf);
	this.seperate(colliding, seperationPriority / 100);
}
```
*This code is from a project that [Simulates Evolution in Intelligent Autonomous Agents](https://umerkk164.github.io/EvolutionSandbox/)
This feature must be used with extreme caution and only where statements succeeding expressions are singular. Generally only include curly braces where you have to encapsulate more than one statement, otherwise, omit them for better readability and less redundancy.

#Conclusion
You might have noticed that I have given particular importance to the fact that code should be easy to expand upon in the future, and it should be neat to look at and comprehend for anyone (not just you). This is one of the key concepts programmers follow. If you have more tips for new programmers, leave them in the comments below.
If you have read this far, you should be tempted to leave a love react and see how happy that makes both of us ;)