My Best 5 JavaScript Tips and Tricks to Write Clean Codes in 2023

As you know, JavaScript is the world’s first programming language, web language, multimedia portable (such as PhoneGap or Appcelerator), server side (like NodeJS or Wakanda) and has many other uses.

It is also the beginning of many new developers in the programming world, as it can be used to display simple warning in a web browser but also to control the robot (using nodebot, or nodruino). Engineers who specialize in JavaScript and coding organized and effective coding have become the most sought after items in the job market.

5 Best JavaScript Tips and Tricks

In this article, I will share a set of JavaScript tips and tricks that should be known to all JavaScript developers regardless of their browser/engine or SSJS translator (Server Side JavaScript).

1. Destructuring Assignment

The demolition function allows the element of one or more objects to be assigned variables in a single sentence. Created variants will have the same name as this place.

let myObj = {
  id: 1,
  name: 'My Object'
};

// without destructuring assignment
let id = myObj.id;
let name = myObj.name; 
// id = 1, name = 'My Object'

// with destructuring assignment
let { id, name } = myObj;
// id = 1, name = 'My Object'

This is very useful if you know that you need to use multiple structures in an object, you need to use the same area multiple times, or the area you wish to use is deeply embedded in that object. In all these cases, using a demolition kit saves you from all the hassles of obtaining object structures by binding and makes your code shorter and easier to read.

For example, I recently worked with Leaflet, a Javascript framework for creating interactive maps. It is customized and allows you to assign your properties to different tags on the map. However, access to these facilities may be somewhat detrimental – we can clean this up with demolition work.

// without destructuring assignment
function onEachFeature (feature, layer) {
  if (feature.properties.hasPopup) {
    let popupContent = `<a href="/feature/${feature.properties.id}">${feature.properties.name}</a>`;
    layer.bindPopup(popupContent);
  }
}

// with destructuring assignment
function onEachFeature (feature, layer) {
  let { hasPopup, id, name } = feature.properties;

  if (hasPopup) {
    let popupContent = `<a href="/feature/${id}">${name}</a>`;
    layer.bindPopup(popupContent);
  }
}

I may have added an extra line of code, but I believe this makes it much clearer and easier to read the purpose of this work now.

It is also possible to destroy the same members, allowing you to assign one or more of those elements to the variable. However, I do not find myself using this syntax very often so I will not include it here again. If you wish to learn more, please refer to the MDN reference.

Lastly, if you use an object with an object as a parameter, it is possible to destroy that object within the parameter list. This saves you the effort to clearly articulate the dynamics yourself, and makes it clear what structures the job requires.

function logPerson(person) {
  let { name, age } = options;

  console.log(`${name} is ${age} years old`);
}

function logPerson({ name, age }) {
  console.log(`${name} is ${age} years old`);
}

2. Short Circuit Evaluation & Assignment

Sensitive operators of JavaScript, AND (&&) and OR (||) are known as short circuit operators because they only test the expression where necessary to determine the effect of the boolean sentence.

For example, ONLY it requires both sides of a statement to check that it is true. Therefore, if the left-hand side of the statement proves false, it does not bother to check the right-hand side as it would be a waste of time.

Similarly, OR requires only one side of the statement to check its validity. Therefore, if the left-hand side checks for accuracy, it does not bother to check the right-hand side.

This brief rotation can be helpful in adding some security to the rhetoric. For example, consider the following activity:

function logIfAdult(person) {
  if(person.age >= 18) {
    console.log("Person is an adult");
  }
}

The problem with this implementation is that you can’t guarantee that a person’s object is not in vain. If you are using this function with an empty person, you will get the following error:

Uncaught TypeError: Unable to read the 'age' feature of null.

For short circuit tests, we may add security such as:

function logIfAdult(person) {
  if(person && person.age >= 18) {
    console.log("Person is an adult");
  }
}

This is because, if the unemployed person will check that the lie (this is because null is a “false” value, if this concept is new to you, please read this article again), and the whole conversation will be short. Only if the person says nothing will the proverb go on to check the right side of the quote, then we know it is safe to check and we will not find any errors.

We can use this short cycle when we assign variables as well. For example, consider the following activity:

function logName(person) {
  let name = person && person.name;
  console.log(name);
}

logName({ name: 'Sam' });
// logs 'Sam'

logName(null)
// logs 'null'

What is happening here? Well in the first example, we pass on the work to a person’s legal object. Because a person’s object is not in vain, the AND operator goes to the right side of the dialog, and assigns the person ‘s value to the name changer. In the second example, a person has nothing so the expression refers to circuits and returns null to the word change.

We can extend this continuously to log in the default name instead of just doing nothing. In this case we are using an operator OR, so we will only use the default value if the personal item is empty.

function logName(person) {
  let name = person && person.name || 'Default Name';
  console.log(name);
}

logName({ name: 'Sam' });
// logs 'Sam'

logName(null)
// logs 'Default Name'

3. Optional Chaining and Nullish Coalescing Operator

Short circuit and task tests are so common that new shorter syntax is added to JavaScript to achieve the same purpose. These coalescing operators are optional and ineffective. I decided to combine both the short circuit and the option of chaining / null coalescing as, at the time of writing, the latter are new features and may not be fully compatible with older browsers.

The chain-of-choice operator (?.) Allows you to get in between items without having to explicitly check that the item is not in vain. If an object is useless, the speech will simply go unnoticed instead of throwing an error. For example, optionally, the logIfAdult function from the top can be rewritten as follows:

function logIfAdult(person) {
  if(person?.age >= 18) {
    console.log("Person is an adult");
  }
}

The nullish coalescing (??) operator is used to return the default value when the left value of the sentence is empty. In this way, it replaces the user ‘s function OR in the log function above:

function logName(person) {
  let name = person?.name ?? 'Default Name';
  console.log(name);
}

4. Callback Tasks

Anonymous jobs can be really helpful – they can be announced when and where you want them, and they are great if you need a job as a single place.

let people = [
  {
    id: 1,
    firstName: 'Sam',
    lastName: 'Walpole',
  },
  ...
];

let viewModels = people.map(p => ({
  id: p.id,
  name: `${p.firstName} ${p.lastName}`,
}));
// viewModels = [{ id: 1, name: 'Sam Walpole' }]

However, since the job does not have a name, leave it to future developers to find out what the code inside your redesign function does – okay here, but for long, complex operations it can waste unnecessary time. By declaring a job first as a named job, you make the code readable faster and give future developers some clues about the purpose of the job.

let people = [
  {
    id: 1,
    firstName: 'Sam',
    lastName: 'Walpole',
  },
  ...
];

let toViewModel = p => ({
  id: p.id,
  name: `${p.firstName} ${p.lastName}`,
});

let viewModels = people.map(toViewModel);
// viewModels = [{ id: 1, name: 'Sam Walpole' }]

5. Enum

Enum is a method of keeping a set of values ​​that do not change as a type. Many languages ​​have built-in enum support, but in JavaScript we have to create our own using something.

const Color = {
  RED: 'RED',
  GREEN: 'GREEN',
  BLUE: 'BLUE',
};

let redCar = {
  make: 'Ferrari',
  model: '812',
  color: Color.RED,
};

let greenCar = {
  make: 'Aston Martin',
  model: 'Vantage',
  color: Color.GREEN, 
};

Enums pair nicely with switch statements for flow control:

function getHexColor(car) {
  switch (car.color) {
    case Color.RED:
      return '#ff0000';
    case Color.GREEN:
      return '#00ff00';
    case Color.BLUE:
      return '#0000ff';
  }
}

Sometimes, though, this may be a little verbose. Instead of using the change statement here, we can use a dictionary. Dictionaries in JavaScript are pronounced in much the same way as enum, but psychologically for a different purpose. When enums are a set of fixed values, dictionaries are a set of key pairs / values.

function getHexColor(car) {
  let hexColors= {
    [Color.RED]: '#ff0000',
    [Color.GREEN]: '#00ff00',
    [Color.BLUE]: '#0000ff',
  };

  return hexColors[car.color];
}

In the example above, we have eliminated the need for a change statement, as we have created a dictionary with enum values ​​as keys, and hex colors as values. By removing all the ambiguity of the change statement, I believe this leads to an easier reading of the code.

Conclusion

In this article I have given 5 tips I often use in JavaScript to make my code shorter and easier to read. I hope you find them useful and you will find opportunities to apply them to your code.

I post mostly about HTML, CSS, JS and Web Development. To make sure that you don’t miss out on any posts, please follow this blog and subscribe to my newsletter. If you found this post helpful, please like it and share it. You can also find me on Instagram.

Leave a Comment