Categories
JavaScript Best Practices

JavaScript Best Practices —Names, jQuery, and Objects

Spread the love

JavaScript is an easy to learn programming language. It’s easy to write programs that run and does something. However, it’s hard to account for all the uses cases and write robust JavaScript code.

In this article, we’ll look at the best ways to name things and deal with objects, names, and jQuery code.

Use PascalCase for Constructor, Class, Singleton or Library Exports

We stick with PascalCase as we do without export for constructors, classes, singleton objects, and libraries.

For instance, we write:

const StudentUser = {
  //...
};

export default StudentUser;

This also applies to constructors and constructor functions:

class StudentUser {
  //...
}

function StudentUser {
  //...
}

Acronyms Should be All Upper Case or Lower Case

Having acronyms all in the same case makes them more readable.

For instance, we can write:

const HTTPResponses = [
  // ...
];

or:

const httpResponses = [
  // ...
];

When Should we Make Constant Names Upper Case?

We can make constant name supper case when the constant never changes.

Having them upper case means that we can trust to not change.

We should also make constant names upper case if they’re exported.

However, that should only apply to the top level.

For instance, we can write:

export const API_KEY = 'foo';

or:

export const FOO = {
  key: 'value'
};

Accessors

We don’t need accessor functions for properties.

Also, we shouldn’t use JavaScript getters or setters as they have unexpected side effects.

They also make our code harder to understand.

Instead, we make functions to get and set our values.

For instance, instead of writing:

class Person {
  get age() {
    // ...
  }

  set age(value) {
    // ...
  }
}

We write:

class Person {
  getAge() {
    // ...
  }

  setAge(value) {
    // ...
  }
}

Normal methods are easier to understand.

Is a Property or Method returns a Boolean, then we Prefix it with is or has

For instance, we write:

person.hasAge()

instead of:

person.age()

Now we know what the function does just by the name.

Creating get and set Functions

We can create get and set functions for getting and setting values.

For instance, we can write:

class Person {
  constructor() {
    //...
  }

  set(key, val) {
    this[key] = val;
  }

  get(key) {
    return this[key];
  }
}

This way, we can get and set the values dynamically by their key and value.

Triggering Events

If we trigger events, we should pass in an object instead of a raw value.

For instance, we write:

const event = new CustomEvent("eventName", {
  "detail": "event"
});
document.dispatchEvent(event);

document.addEventListener("eventName", (e) => {
  console.log(e.detail);
});

Now we have an object as the value of detail instead of a primitive value.

If we always send an object with an event, then we won’t have to check if the object sent is a primitive value or an object.

jQuery

If we use jQuery , we should add a $ prefix so that we know it’s something returned by jQuery.

For instance, we can write:

const $main = $('.main');

Cache jQuery Lookups

If we look up something with jQuery, we should cache them so that we don’t have to look up the same thing repeatedly.

For instance, we can write:

const main = $('.main');
main.hide();
// ...

main.css({
  'background-color': 'green',
});

Use find with scoped jQuery Object Queries

We shouldn’t use find to make scoped queries.

Instead, we just use one CSS selector with one query:

$('.main ul').hide();

This way, we only do the lookup once rather than twice.

Arrow Functions

We should use arrow functions as much as we can for callbacks.

For instance, we write:

[1, 2, 3].map((x) => x + 1);

It’s much shorter than using traditional functions.

The value of this also doesn’t change inside it.

Skipping Braces

We can skip the braces and use implicit return if our function is one statement long.

The example above showed us that we can skip the braces and return something.

We wrote:

(x) => x + 1

which returns x plus 1.

Conclusion

To make things speedier when using jQuery, we should cache our queries.

Also, we shouldn’t use find to make scoped queries. Instead, use one CSS selector.

We should stick to standard JavaScript naming conventions.

And we should use the get and set keyword for accessors.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *