3 Ways to Write Elegant JavaScript Code

javascript code,codecademy javascript,javascript code examples,javascript code editor,get type javascript,javascript,javascript tutorials,each javascript,javascript tutorial,

elegant javascript

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

javascript code,codecademy javascript,javascript code examples,javascript code editor,get type javascript,javascript,javascript tutorials,each javascript,javascript tutorial,
 
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 => (
        <ListItem person={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 <ListItem/>. 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 

javascript code,codecademy javascript,javascript code examples,javascript code editor,get type javascript,javascript,javascript tutorials,each javascript,javascript tutorial,

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

javascript code,codecademy javascript,javascript code examples,javascript code editor,get type javascript,javascript,javascript tutorials,each javascript,javascript tutorial,

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 => (
        <div>{element}</div>
      ))}
    );
}  
 
The reason why this is a bad example is that the Example component should only be responsible for displaying the data on the screen, not fetching the external data. This creates clutter and makes the component harder to debug. Fortunately, we can fix this by writing our own hook that contains the logic for making a post request. This hook will be a function that accepts a URL and options, makes the post request, and returns the data. The codebase just became much more maintainable by making this change.
Thanks for reading!
 
 
 
 

Post a Comment

Previous Post Next Post