DEV Community

loading...
Cover image for 3 Ways to Write Elegant JavaScript Code

3 Ways to Write Elegant JavaScript Code

Animesh Dhanuk
PHP Developer with 8+ years of experience.
Originally published at cmsinstallation.blogspot.com ・2 min read

Whenever I take a look at some older code, I always try to find ways to refactor and improve readability. Methods of doing this can include writing custom React hooks, wrapping repeated code into subroutines, and others. In this post, I’ll be sharing three common methods to modularize and improve the maintainability of your code.

1. Use Typescript

This may come as an eye-roller for some, but Typescript alleviates many of the issues that make JavaScript an unsafe language in some cases. It also makes the intentions of your code clearer.Let’s see a small JavaScript example:

import React from 'react';
import ListItem from './ListItem';

const People = ({ peopleList }) => {
return (
{peopleList.map(person => (

))}
);
}

export default People;

We can see here that People accepts peopleList as props, which is a list of objects each representing a person which will be rendered as a . All of this is fine, but what if a property is missing from one of the people? What if a person has undefined as their occupation or salary? A lot of you might be thinking that we can just use prop-types to handle this, but in my opinion, Typescript provides a more elegant solution.

2. Use IIFEs

If you’re familiar with Immediately Invoked Function Expressions, then you definitely know how useful they can be as a clean way to compose two statements into one. Let’s say you wanted to initialize an array with some external data:

import { data } from './data';

const initList = () => {
const arr = [];
for (const element of data) {
arr.push(element);
}
return arr;
}

const dataList = initList();

In this example we’ve defined a function initList which returns an array containing the external data. We then call the function and store the result in dataList. It’s not that there’s anything wrong with this code.

3. Separation of Concerns

It is always important to separate the concerns of functionality in a code base, especially when working with projects of increasing complexity. It is typically not ideal to have a function perform multiple tasks at once, especially if they are in no relation to each other. Let’s analyze a bad React example of a component Example that is dependent on some external API data:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const URL = "http://somehost:someport/some/path";

const Example = () => {
const [data, setData] = useState([]);

const options = {
method: 'POST',
body: JSON.stringify(sampleBody),
}

useEffect(() => {
(async () => {
try {
const response = await axios.post(URL, options);
if (response) {
setData(response.data);
}
} catch (error) {
console.error(error);
}
})();
}, [data]);

return (

{data.map(element => (

{element}

))}

);

}

Discussion (0)