Using ChatGPT for productivity in JavaScript: Quick wins
Tags: javascript, programming, ai, chatgpt
Published: 2023-03-29 13:46:07

If you’ve been anywhere on the internet in the past few months, you’ve seen AI plastered all around. There’s no escaping it. And there’s a good reason for this. It’s actually quite revolutionary when it comes to usefulness and productivity. But now it’s time to integrate AI into your work, and I’m here to tell you how.

There are a few tools out there that are useful to you as a software developer, but for now, let’s look at ChatGPT. There’s also GitHub Copilot, which can do similar things as discussed below but works slightly different, so that’ll have to wait for the next blog post.

All of the examples below are generated using ChatGPT-4, which is not yet available for everyone. The current ChatGPT model available to everyone is GPT3.5, so keep that in mind.

_**General warning: ChatGPT can generate incorrect or very unoptimized code (or both), validate your responses, and understand what it’s doing. Sometimes even asking ChatGPT to optimize or fix the code it just provided will generate better results as well.**_

## Extracting Styling
ChatGPT is a language model, but it can do conversion extremely well. Take a React component that has inline styling. This is ugly and typically not recommended. This is some of the styling I got.

```js
const defaultStyle = {
    display: 'inline-block',
    borderRadius: '8px',
    padding: '10px',
    background: 'linear-gradient(to bottom, white, lightgrey)',
    boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
    transition: 'all 0.3s ease',
  };
```
But this is something I would prefer to see in CSS and a module.css file at that. You can very easily paste your entire react component to ChatGPT and ask:

```
Can you convert this styling to be in a module.css file
```
It will generate the css for you:

```css
.roundedBox {
  display: inline-block;
  border-radius: 8px;
  padding: 10px;
  background: linear-gradient(to bottom, white, lightgrey);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}
```

And then it’ll tell you how to import, and apply the style.

```js
import styles from './RoundedBox.module.css';
// [ more code ]
<div className={styles.roundedBox} {...props}>
```
There are some tweaks you can make and some suggestions you might not use. But… the conversion is correct and working.

## Generating helper functions
Sometimes there are little things you need doing, that are specific to your application. You can use ChatGPT to create this helper function for you by specifying the input and the output, and then tell them what kind of code it needs to generate.

You can also provide the test as the input and ask ChatGPT to write a function that works on the test, as a Test Driven Development kinda way. But for now I’m not going to do this.

This was my input to generate the function.
```
I need to convert a string to a list of words and their count, 
and the array need to be structured like this:
 [{“word”: “myword”, “count”: 5}]
It needs to be in JavaScript and needs to be short and concise, and readable
```

And then I got this as a return value
```js
function countWords(str) {
  const words = str.split(/\\s+/);
  const wordCount = {};
  words.forEach(word => {
    wordCount[word] = (wordCount[word] || 0) + 1;
  });
  return Object.entries(wordCount).map(([word, count]) => ({
    word,
    count
  }));
}
const inputString = "example string with words and words and example";
const result = countWords(inputString);
console.log(result);
```

It even outputted the result for me, which was a nice bonus. It might not be entirely optimized or follow the guidelines you’d like to follow, but it generates code that actually works and does what you need it to.

## Writing tests
Yes, it’s not Test Driven Development, but I asked ChatGPT to generate a test based on the function above using Jest. It even gave me instructions how to install Jest, how to add it to my project and how to name my test file. And the test it came up with was:

```js
// countWords.test.js
const countWords = require('./countWords');
test('Counts words in a string', () => {
  const inputString = "example string with words and words and example";
  const expectedResult = [
    { word: 'example', count: 2 },
    { word: 'string', count: 1 },
    { word: 'with', count: 1 },
    { word: 'words', count: 2 },
    { word: 'and', count: 2 }
  ];
  expect(countWords(inputString)).toEqual(expectedResult);
});
```

I followed the Jest installation instructions from ChatGPT, and behold; my test ran successfully.

```bash
PASS  ./test.test.js
  ✓ Counts words in a string (1 ms)
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.171 s, estimated 1 s
Ran all test suites.
```

To loop back on the “Generating helper functions” section above, I pasted this test to ChatGPT in a different thread and asked it to write a function for me, and it provided me with pretty much the same code as the one generated there.

## Writing JSDoc
Very straightforward, but something very useful as well. ChatGPT can write `JSDoc` for any function you give it. Just provide the code, provide the request you need `JSDoc`, and you’ll get something like this:


```js
/**
 * Takes a string and returns an array of objects containing each unique word
 * and its count within the string. The output array has objects with the
 * structure: { "word": "example", "count": 2 }.
 *
 * @param {string} str - The input string to process.
 * @returns {Array.<{word: string, count: number}>} An array of objects, each
 *   containing a unique word and its count in the input string.
 */
function countWords(str) {
```

This can be incredibly useful for making documentation, adding auto-completion, and adding readability. Especially if you work with multiple people on a team.

## Convert JS to TS
Yes, you can use ChatGPT to convert JavaScript files into TypeScript. Though I will state once again, make sure to validate the response. It can return incorrect conversions or just make mistakes. However, I’ll show you the TypeScript I got generated from ChatGPT, which still works as expected.

```js
// countWords.ts
interface WordCount {
  word: string;
  count: number;
}

function countWords(str: string): WordCount[] {
  const words = str.split(/\\s+/);
  const wordCount: Record<string, number> = {};
  words.forEach((word) => {
    wordCount[word] = (wordCount[word] || 0) + 1;
  });
  return Object.entries(wordCount).map(([word, count]) => ({
    word,
    count,
  }));
}
export default countWords;
```

## Conclusions

So now that you see what ChatGPT can generate for you, you can imagine the time you can save by letting ChatGPT do some of the work for you. However, it’s not something you can just copy-paste and be done with it, like you’ve always done with StackOverflow. You need to ensure you understand what is returned, if the returned value is the best way to do something, and if it didn’t introduce any bugs or incorrectness into your code. Maybe it assigned the wrong type when I converted to TypeScript, maybe it misses edge cases when generating tests, and maybe it has wrong texts in the JSDoc it has generated.

Your go-to flow should be:

- Request what you need from ChatGPT.
- Validate that what is generated is actually solving your request.
- Validate the code against manual/automated testing.
- Walk through the code to make sure it’s up-to-date, follows best practices, is optimized, and doesn’t do things it should absolutely not do

In general, once you get to work with ChatGPT more, you’ll learn to spot where it can make mistakes, and what it’s good in. I never validate converted CSS for example, but I do test TypeScript conversion and JavaScript functions myself.