JavaScript Best Practices — Variables and Strings
Tags: javascript, career, codenewbie, codequality
Published: 2020-10-04 00:06:09

---
title: JavaScript Best Practices — Variables and Strings
published: true
date: 2020-08-08 23:36:23 UTC
tags: JavaScript,careers,codenewbies,codequality
canonical_url: https://thewebdev.info/2020/08/08/javascript-best-practices%e2%80%8a-%e2%80%8avariables-and-strings/?utm_source=rss&utm_medium=rss&utm_campaign=javascript-best-practices%25e2%2580%258a-%25e2%2580%258avariables-and-strings
---

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**

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 best practices we should follow when writing JavaScript code.

### Variable and Function Naming Conventions

We should have variable and function names that are clear.

In JavaScript, names are usually camelCase except for constants and constructors.

For example, we can write:

```
const firstName = 'james';

```

We name constants with:

```
const MAX_RETRIES = 50;

```

And we name constructors and classes with PascalCase:

```
class Dog {}

```

### Using Global Variables

We want to avoid creating global variables.

They’re accessible everywhere so they can be modified by anything.

That leads to hard to trace issues.

So we should share variables with other ways like modules.

### Functions

Functions should do one thing at a time.

If it has to do more, then we should separate it into a helper function.

### Progressive Enhancement

We shouldn’t assume that everyone has JavaScript enabled.

To display something to users that don’t have JavaScript enabled, we can put stuff in the `noscript` tag for them.

### Don’t Change Variable Type After Init

To make our lives easier, we shouldn’t change the variable type after a variable is initialized.

For example, we shouldn’t write:

```
let status = "Success";
status = 1;

```

Changing types makes debugging harder.

Instead, we can assign values with different types to different variables.

### Use Inline Commenting

We can add inline commenting in our code for comments.

We should keep them short and to a single line.

For example, we can write:

```
addtoCart(order) // add to cart

```

### Control Variable Scope

To control variable scope, we can use `let` and `const` .

They’re all block-scoped so there won’t be any confusion as to where they’ll be available.

For example, we can write:

```
for (let i = 0; i < 10; i++) {
  console.log(i);
}

```

We use `let` to define `i` so that it’s only available within the loop.

### JavaScript is Case-Sensitive

We should remember that JavaScript is a case sensitive language.

So `foo` is different from `Foo` .

This applies to everything.

So we should make sure our code has the right case.

### Traverse an Array From the Right End

We can traverse an array from the right end with the array instance’s `slice` method.

For instance:

```
const arr = ['a', 'b', 'c', 'd', 'e', 'f'];
console.log(arr.slice(-1));

```

returns `['f']` and:

```
console.log(arr.slice(-2));

```

returns `['e', 'f']` and so on.

`slice` doesn’t modify the array is called on.

### Substitute Loop with map()

If we want to map array entries from one thing to another, we don’t have to use a loop.

Instead, we use the `map` instance method.

For example, we can write:

```
const itemsIds = items.map((item) => {
  return item.id;
});

```

to get the IDs from items in the `items` array.

### Replace All Occurrences of a String

We can call `replace` with the `g` flag to replace all occurrences of a string.

For example, we can write:

```
const str = "foo foo bar baz";
console.log(str.replace(/foo/g, "qux"));

```

Then `‘qux qux bar baz’` is returned.

### Conclusion

There’re many tricks we should be aware of to improve our JavaScript code.

The post [JavaScript Best Practices — Variables and Strings](https://thewebdev.info/2020/08/08/javascript-best-practices%e2%80%8a-%e2%80%8avariables-and-strings/) appeared first on [The Web Dev](https://thewebdev.info).