JavaScript Best Practices for Beginners
Tags: javascript, react, webdev, codenewbie
Published: 2021-09-25 07:26:32

Let us quickly discuss some of the best practices which you can follow while working with JavaScript. I have covered some of the basic stuff which we will be using often in our day-to-day programming.

Let’s get started.

### Always define variables using let or const

By defining variables using `let` or `const`, we can avoid problems such as
- **Pollution of global variables and namespaces**: Let’s say your application uses a global variable `title`. In some other part of your code, you have defined a variable `title` (without `let` or `const`) again, but this variable is specific to that function and it is nowhere related to the global variable `title`. Then there might be a chance this `title` variable might mutate (change) the global value.

![Pollution of global variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e8bpuxdemzv5quddvabs.png)

- If we define the variables using `let` or `const`, the variable will be blocked scoped meaning it’s only available to that block of code. Hence it will not be able to change the global variable.

![Remediation for pollution of global variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/of2c3kp6f5lpe9c8xagd.png)

- **Exposing sensitive data**: Let’s say you are storing the API key in a global variable (which you defined without `let` or `const`), then this API key will be stored in the global object (`window`) and can be easily accessed by anyone visiting your site.

![Sensitive data can be accessed from the global object (window)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ailjp7w3jc4qz6rbyebq.png)

- Again if we define the variables using `let` or `const`, the variable will be blocked scoped and it will not be exposed to the global object (`window`).

### Always define conditions correctly

- If you want to check a variable for falsy values (`undefined`, `null`, an empty string), simply use NOT operator (`!`) instead of checking each and every falsy value.

![Checking falsy values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g96zgwb6zsjp9q9kbg6v.png)

- If you want to check if a key/value is present in an object. You can safely check one by one if that key/value exists using AND operator (`&&`).

![Checking if object key/value exists or not](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x6bu22s9zplamfjivvlw.png)

- You can also use optional chaining to check whether a key/value is present in an object or not.

![Optional Chaining](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhz9mnv870x2zi9z55hl.png)

### Semicolon

Before we dive deep, here is an activity for you. Can you guess what will be the output of the below function?

![What will be the output of the console?](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kld2t6vem77knu7cmvse.png)

**Answer**: The output will be `undefined` 😲. But how?, This is because of automatic semicolon insertion by JavaScript Engine while parsing the code. If the code is not formatted correctly like in the above example, JavaScript Engine will add a semicolon(`;`) to the end of the return statement (`return;`) and it thinks that no value is returned. So returns a value as `undefined`.

> _**Automatic Semicolon Insertion (ASI)**: At the time of parsing the code, JavaScript Engine automatically inserts a semicolon at the end of each token. This sometimes may cause unexpected behavior of code. You can read more about it [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion)_

![Automatic Semicolon Insertion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8pdq3h1cz481ko920qye.png)

It is also recommended to add a semicolon at the end of each statement of the code to avoid ASI problems.

### Brackets

People from different programming language backgrounds tend to start the braces in the next line. But in JavaScript, this can cause unexpected behavior of the code.

- Never start the curly braces (`{}`) in the next line. Because of ASI, your code may behave unexpectedly.

![BAD Brackets](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wk63l2qdhbi8mtgriu2a.png)

- Always start the curly braces just after the end of the statement (in the same line).

![GOOD bracket](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/atup7d9lwhkclevysh9f.png)

> _We can avoid these problems, by formatting the code using [Prettier](https://prettier.io/) or any other formatting tools/libraries._

### Template Literals

Template literal is used to define a string value. Template literals are enclosed by the backtick and dynamic values/placeholder can be passed using the dollar symbol `${dynamicValue}`.

![Example for Template Literal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x0idpppngxagb4xr5q3h.png)

Below are some of the use cases of template literals.

- Template literals can be used to define dynamic HTML content.

![Defining dynamic HTML content using template literals](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vkkfppk48bbkg34uvaai.png)

- Template literals can be used to define database queries

![Defining DB queries using template literals](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8wlwwmfc6y0rhb0pm25g.png)

- Template literals can be used to define dynamic shorts URLs (single line).

![Defining short URLs using template literals](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gd6mvl6klprw1dhqkpqq.png)

- **Do not use** template literals to define long URLs with multi-lines. As APIs do not support the multi-line URLs. There are many workarounds available to handle multiple parameters in a single line, but we are not going to discuss all of that here.

![Avoid template literals for long multi-line URLs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8g7pt7q32wmp4w5wx2sy.png)

> _We can avoid most of the problems discussed in this article by using linters and code formatters. Here are some of the popular linters and code formatters._
_**Linters**: [ESLint](https://eslint.org/) , [JSLint](https://www.jslint.com/)_
_**Code formatters**: [Prettier](https://prettier.io/)_

That’s all I have for today. Hope you enjoyed it. 😉

You also check out my article on [Naming variables and functions in JavaScript](https://dev.to/syedafrozpasha/naming-variables-functions-and-classes-in-javascript-41m4).

Thank you for stopping by. If you like the content do support me and follow me for more content like this.

<a href="https://www.buymeacoffee.com/SyedAfrozPasha"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=SyedAfrozPasha&button_colour=FFDD00&font_colour=000000&font_family=Cookie&outline_colour=000000&coffee_colour=ffffff"></a>

Connect with me on [LinkedIn](https://www.linkedin.com/in/syedafrozpasha/), [Twitter](https://twitter.com/SyedAfroz_Pasha), and [GitHub](https://github.com/SyedAfrozPasha).