How You Can Use AI to Improve Your Programming Skills
Tags: chatgpt, javascript, ai, programming
Published: 2023-02-01 08:27:16

_I’ve seen a lot of people write about AI, and how it will disrupt everything. While it is true it’s truly amazing, it’s not there yet. Tools like GitHub Copilot and ChatGPT are most frequently mentioned, but how can you leverage them to your benefit?_

So let’s get this out of the way first. AI is not here to replace programmers. It never will. *knocks on wood*. However, it is there to make the programmers life easier. But first a look back a few years.

I’ve been in software development, professionally, since 2008, and as a side-gig a few years before that. So I could say I’ve seen some earlier transitions. In 2008 there were no frontend frameworks like we know today. jQuery came out in 2006, and that was one of the few popular ones. And UI libraries, like Backbone, started releasing around 2010.

The framework landscape was very different. And with the advent of massive time-saving frameworks like React and Angular, came the fear it would reduce the workload enough people would be fired. But look at us now, even with the massive amounts of layoffs happening everywhere, there still is a shortage of developers.

Take it back further a few years, when I was still in high school and exploring what to do after, I landed on “Communication and Multimedia design” with the intention of improving my programming skill-set and get some extra knowledge in related activities such as av-design and 3d modeling. But while exploring I noticed a trend, everyone recommended not to go in the field of programming, as it was predicted there would be a surplus of developers as we’d reached the peak. Considering this was 2005, only a few years after the dotcom bubble, I could imagine people being afraid of this “Web2.0”, but it turned out alright for everyone.

Anyways, back to 2023. AI is here, we’ve got AI like ChatGPT and GitHub Copilot for text-based AI, there’s DALL-E and Midjourney for images, Microsoft can replicate your voice, Apple has AI narrated books, and the list goes on. It all seemed to be coming from nowhere and now everyone is talking about it.

And with the talking, comes the fear to be made redundant. And I think this is not something we’ll see in the near future. If anything, it will make us more optimized, which means, we can collectively do more work. And with more work, more inspiration, and the ability to produce more faster, comes more inventions, more ideas and more demand for programming.

If you’re currently working at a company as a programmer (or related position) you probably know your list of tickets is longer than you (and your team) can ever complete. This is some sort of paradox that just keeps on going, even after a massive cleanup. Maybe you could get a little more done with the use of AI.

And of course, this might pave the way for one-man “teams” who can do things previously not possible to do alone, and this might be a new era of startups changing the internet, again. But I guess that is the optimist in me talking.

## Using AI to improve your programming

Alright, you read my rambling about AI and an optimistic view, but not yet where you can here for. How can you use AI to improve your programming.

I’ve seen people use the result of AI’s directly, and while this may work, this isn’t improving your work, this is the equivalent of copy/pasting a StackOverflow answer. Sure, you could, maybe, write a simple back-end in a language you’re not familiar with ,or you could convert comments and variable names to a language you don’t speak, but none of that is actually productive.

_Don’t do this though, don’t blindly copy-paste anything from ChatGPT without knowing what it does, and if it even works/does what you ask it to._

```csharp
using System;
using System.Security.Cryptography;

public class ConvertidorISO
{
    public static int ConvertirANumeroAleatorio(string fechaHoraISO)
    {
        // Convertir la fechaHoraISO a un arreglo de bytes
        byte[] datos = System.Text.Encoding.ASCII.GetBytes(fechaHoraISO);
        // Utilizar el algoritmo SHA256 para crear un hash de la fechaHoraISO
        byte[] hash = new SHA256Managed().ComputeHash(datos);
        // Convertir el hash a un entero y devolverlo
        int numeroAleatorio = BitConverter.ToInt32(hash, 0);
        return numeroAleatorio;
    }
}
```

The above is the code it gave me when I asked it to write a function in C# to convert a ISO timestamp to a random number, in Spanish. I don’t speak Spanish, and I’ve never programmed in C#, so the methods it’s calling are unknown to me, and I don’t know if they exist or do what ChatGPT tells me they do. So if one of the readers can confirm this code works that would be great. After this prompt ChatGPT also started just talking Spanish to me, so I guess it suddenly thought I was Spanish. And furthermore, I doubt it actually does what I told it to do.

This however is a prime example why you should not just blindly copy/paste code an AI gives you, you need to actually know it works, and does what it says it does. ChatGPT can confidently lie, and sometimes even back it up with sources (which don’t confirm the lie at all). Though often it seems I get code that, at least, mostly works. So I can semi-confidently say the code above should, probably, work.

However, imagine this scenario. You’re working on a ReactJS application, and you want to get some inspiration/help from an AI. What you could do is let it help you, instead of doing the work for you.

I recently wanted to make a background of a React Application black with randomized stars scattered around the screen, to give the illusion of being “in space”. I could’ve written it myself, no problem there, but I didn’t feel like figuring out colors to use, Unicode characters to pick and what that CSS was again for absolute positioning and screen-dependent font-sizes, so I asked ChatGPT: “Can you give me an array of realistic colors suitable for stars”. It did, it gave me about 10 colors in yellowish and whiteish tints. I asked it to add some blueish and orangeish colors, and it came up with a complete array of nice colors.

```javascript
["#F5A623","#F39C12","#F1C40F","#F7DC6F","#FDEBD0","#F5B041","#F8C471","#F9E79F","#F4D03F","#F7DC6F","#F2C94D","#F08080","#F28482","#F1948A","#F5A4A9","#F8B1B3","#F7C6C7","#F9D9D9","#F2E6E6","#F2E8E8","#F7CECE","#f7f7f7","#d9e6f2","#d0e0f4","#c4e6f4","#c2e0f4","#c1d9f2","#c2c8e6","#f7f7f7","#f7f8fb"]
```

But note, I didn’t get this array presented to me like this, it wrote some code around it, and since then I’ve put it in my own repository and my formatter put every color on a new line. And while this is nice, it doesn’t work well in an article, so I, just now, asked ChatGPT to minify it for me, and so it did.

You also might notice, if you scrolled in the array above, it started using lowercase characters for the colors instead of uppercase in the first 20 or so. Of course one request to ChatGPT can fix that.

This is one of the strengths of using ChatGPT, you can ask it to do something very specific, and it’ll do it happily.

So what about those Unicode characters you ask? Well this is what it came up with, which I like a lot.


```javascript
const stars = ["★", "✶", "✴", "✵", "✪", "❂", "⚜", "⚘", "⚚", "⚛", "⚙"];
```

Then came the next question I asked ChatGPT: “can you create a randomized amount of stars on a randomized position on the screen”

And one of the snippets of the code it gave me was this:

```javascript
const [starData, setStarData] = useState([]);
    useEffect(() => {
        setStarData(generateStars(Math.floor(Math.random() * 50) + 50));
    }, []);
```

The generateStars function looks like this:

```javascript
function generateStars(n) {
    return Array.from({ length: n }, () => {
        return {
            character: stars[Math.floor(Math.random() * stars.length)],
            left: `${getRandomNumber()}%`,
            top: `${getRandomNumber()}%`,
        };
    });
}
```

This is not a piece of code I would’ve come up with. I probably would’ve classically done a `for` loop, but I dig this response and it looks like a smart solution. For the purpose demonstrating the viability of using ChatGPT I actually used this function, where I would probably have written this myself in any other case. But it shows AI can generate code that’s very usable.

But, in the process of getting this code, it initially wrote styling right in the code, didn’t use absolute positioning at first, and the style it did generate was not the kind I’d like to see.

But here’s the key, I knew what I was doing, I wasn’t going in blindly. I had never used the `Array.from` method before, so it let me learn about a new Array method and how to use it, and in the end the result it gave me was tweaked to make it more readable and structured.

While making it more readable, I wanted to strip away `css-in-js`. I wanted it back in the `css` files, as I like my code clean. So I copied the styles JavaScript object it had generated previously (and I had tweaked after to make it do what I wanted to do), pasted it to ChatGPT and asked it to convert it to CSS. It did, and it worked perfectly. It even told me what it had changed, so again, I learned in the process. Of course, after the conversion I validated it had actually converted every property, and made sure they all worked as expected.

**So how does this help me?**
Well that should be quite clear, you can ask it to do specific things you know how to do or have a an idea in the general direction, and validate the response. It would’ve taken me quite some time to come up with the 30 colors it generated. And scrolling through a list of Unicode characters would have been time intensive too, so that helped.

**Remember how I told you it can lie confidently?**

I just asked ChatGPT, for the paragraph above, how many items there were in the array. And it flat out told me, “There are 42 items in the array.”

Which, isn’t true. So this is how the conversation went. Of course I had to make a joke first.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eri7319ye67pv5s5dlne.png)

It apologized it was wrong, and then it gave 43 as the answer. Pestering it again it was wrong again, it replied with 45. Not sure what is up with that, but it clearly wasn’t counting my array. Right after that it started error-ing out for me, so maybe I broke it in the process. If it went down just now, I’m sorry, it broke on 42. Ironic?

## But there’s more than just ChatGPT

So let’s continue, there’s indeed more than just ChatGPT. I’ve been also experimenting with GitHub Copilot. And no, this section is not sponsored by GitHub (I wish, hah), I’m still in the 60-day trial, and most likely will pay after it ends, as it really helps me.

As you might see in the code provided above, I didn’t actually include the color for the stars. This is because my original prompt to ChatGPT was just for random stars, not colored stars. This is also key with working with AI, you will have to give it specific prompts, so you know they’re actually giving you responses you can work with. The more complex the prompt, the bigger the chance you’ll get a broken result.

But yeah, moving on from ChatGPT. I used GitHub Copilot to help me implement the colors. I pasted the array of colors in my file.

```javascript
const  starColors = ["#","#"]
```

And then I went to this code:

```javascript
const style = {
    left: star.left,
    top: star.top
};
```

I typed a `,` after the `top: star.top` line, and it automatically auto-completed with this:

```javascript
color: starColors[Math.floor(Math.random() * starColors.length)],
```

I hadn’t asked it anything, no comments, no suggestion, only the fact I pasted the colors array on top did the trick. Perhaps it looked into the name of the array or the properties within the `style` object, but nonetheless, I hadn’t had to write that line. I didn’t even write `color:` to get it autocompleted correctly.

And that line is exactly what I wanted to achieve. I knew what I wanted, I was already going in to write exactly that line, and it fixed it for me. This being at 11pm, I might’ve even forgotten about `Math.floor` and used `Math.round` instead. For some reason a mistake I regularly make, but that might be because I don’t often get random items from arrays, especially considering I’m a Developer Advocate for my day-job, I program less than I’d like.

So how did it help me in the end? I spent just 10 seconds implementing the color style, where I would’ve spent 30–60 seconds on it normally, plus I might’ve hit a small bug that would’ve caused me to spend another few minutes on it figuring out why my code was wrong in the first place. In the end, this one saved me time!

And those improvements, cutting 30–60 seconds down to 10, doesn’t seem like much. But if it happens 10 times in an hour, you saved yourself up-to 10 minutes already. And that’s a low estimate based on my experience, usually I get these kind of suggestions constantly and probably get close to double my productivity.

## So how can I learn?

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ygb5q5g37d8ao7o5h42.png)

Well one the methods you could use, is [Rubber Ducking](https://en.wikipedia.org/wiki/Rubber_duck_debugging). A method of debugging code.

I, on purpose, created an error in a `JSX` snippet, and I asked it what was wrong. And it quickly spotted my mistake. Of course I could’ve quickly spotted this myself by just trying to run the code. Or my IDE could point it out (it did), but this is a matter of demonstration.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gyoxgtby8v9bu2ixc2q0.png)

Let’s take a look at an earlier mistake I pointed out, using `Math.round` instead of `Math.floor`. Would it be able to spot the mistake itself?

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ltotsr98758am1e3duo.png)

Funnily, it actually said it couldn’t be because of `Math.round`. Yet another example why ChatGPT lies. Questioning it further it actually did give me the right answer, which is all what Rubber Ducking is actually about. You need to dumb things down enough, step by step, to get to the problem. It’s not called `Senior Devving` for a reason, a Rubber Duck will never answer your questions, as it cannot speak (I hope).

So by dumbing things down, you’ll get to the answer. Don’t assume ChatGPT will solve your problem, but it can be a second person you can voice your frustrations to.

### Explain my code
ChatGPT can explain your code for you, even if it is minified. I took the `generateStars()` function I spoke about earlier, and let ChatGPT [codegolf](https://en.wikipedia.org/wiki/Code_golf) it for me, it made this mess:

```javascript
g=(n)=>Array.from({length:n},()=>({c:stars[Math.floor(Math.random()*stars.length)],l:`${getRandomNumber()}%`,t:`${getRandomNumber()}%`}))
```

Now, this code suddenly is a mess, and it’s quite difficult to find out what it does, but ChatGPT comes with the solution. I pasted this code, and asked it to explain it for me, and it came up with this:

```
The function uses `Array.from()` to create a new array with length
"n". The second argument to `Array.from` is a function that creates an
object for each element in the array.

The object has properties "c", "l", and "t" with values assigned as:

- "c" is assigned a random value from "stars" array.
- "l" is assigned a string of random number + "%" sign.
- "t" is assigned a string of random number + "%" sign.

The function creates an array of objects with random values. The
function call `getRandomNumber()` is not defined, it could be a user
defined function.
```

As you can see, it’s capable of understanding the code quite well, and even if it missed a few details and cannot understand context, it could help you understand the code. You can also do this with the code your coworker produces that no one understands.

From here it can actually de-minify the code as well, in case you want a nicer read.

```javascript
function generateArray(n) {
  return Array.from({ length: n }, () => {
    const c = stars[Math.floor(Math.random() * stars.length)];
    const l = `${getRandomNumber()}%`;
    const t = `${getRandomNumber()}%`;

    return { c, l, t };
  });
}
```

### Learning from Github Copilot

So then there’s Copilot. And you can learn from it too! But most importantly, it will help you write comments!

Let’s say you’re going to write a function that will generate a random number between a min and a max. Oh fun fact, that was actually how the code came to be, the one I purposefully changed from Math.floor to Math.round. I generated this code by writing a comment first.

```javascript
// This function takes in a min and max value and returns a random number between the two
```

And then, without any further prompts, it autocompleted the code I wanted to have.

And while the comment here is a bad example, because comments should explain the why, not the _what_ (as that should be self-evident), it still demonstrates the ability of Copilot to generate code with a commented instruction.

### Writing JSDoc

CoPilot is very capable of writing JSDoc comments above methods. As an example, which ties into my “stars” background from earlier, I have a function that generates a random asteroid with random composition based on a pre-defined array. My code is very simple:

```javascript
function generateAsteroidComposition(amountOfMaterials) {
    const mats = [...MATERIALS];
    let pickedMaterials = pickMaterials(mats, amountOfMaterials);
    return pickedMaterials;
}
```

I added the JSDoc code above it

```javascript
/**
 * 
 */
```

And after typing a space after the 2nd row `*` , GitHub Copilot suggested the following:

```javascript
/**
 * Generates a random asteroid composition based on the materials array
 * @param {number} amountOfMaterials - The amount of materials to pick
 * @returns {array} - An array of materials
 */
```

As you can see, Copilot dove into the `pickMaterials` function to determine the logic and the return value, and knows what the `generateAsteroidComposition` does.

When doing the same with the `pickMaterials` function, which I haven’t shown you, it gives me this `JSDoc`, including an example!

```javascript
/**
 * Picks materials from the materials array
 * @param {array} materials - The materials array
 * @param {number} count - The amount of materials to pick
 * @returns {array} - An array of materials
 * @example
 * // returns [{name: "iron", probability: 15, value: 0.15, weight: 100}]
 * pickMaterials([{name: "iron", probability: 15, value: 0.15}], 1)
 */
```

It’s not 100% correct, as the return doesn’t have the "value" property, but that’s the only thing I can complain about, as it does the job perfectly otherwise. Would you have done this with code you do not know, it would most certainly given you insights into _what_ the code does, **and** it would add documentation to the code, you only need to validate manually after.

## Conclusion

AI is great, really. It can help cut down effort to write code, it can be a rubber duck, it can autocomplete code you didn’t even know worked, and it can give you ideas how to solve problems you had no idea how to tackle.

But there’s a caveat, **it can lie, confidently**. Take every answer with a grain of salt, and confirm every answer it gives you by validating the code and solutions.

Overall, AI is mostly a performance-increasing tool. You still have to know programming and have the programming mindset to use AI to code. It hasn’t replaced programming, it will make it easier. Just like it’s easier to write in languages such as JavaScript and C# as opposed to binary.

Furthermore, this article was written at the time ChatGPT was in the January 9th version and free. Rumors go around it will cost $42/month after it will go paid. That amount might seem like a lot, but if you are freelancing as a software developer, you most likely charge twice that amount, per hour. This tool will save you 30 minutes a month easily ,so it is absolutely worth it. Just like the $10/month or $100/year for GitHub Copilot.