Advertisement
  1. Code
  2. JavaScript

Tips for Generating Code With ChatGPT

Scroll to top
6 min read

ChatGPT is a true superpower not just at writing, but also at generating code. Getting started with ChatGPT is straightforward, but if you want to get the most out of it, then you need to learn how to craft good prompts.

Prompts are instructions or discussion topics that you provide for the ChatGPT AI model to respond to. They can consist of a question, statement, or any other query that you want to use to spark creativity, reflection, or engagement.

There are several hidden prompts and formulas that you really need to know about to use ChatGPT effectively. Implement these formulas in your prompts and get the best results from ChatGPT.

Be Specific With Your Prompts

When using ChatGPT, you want to avoid simplistic prompts. The more specific you can be in your requests, the better.

The way you can look at this is not to treat ChatGPT as a vending answer machine where you put tokens in and it spits out the answers. Instead, you want to treat ChatGPT as your personal assistant (whether it's for generating content or code).

To make your queries as detailed and specific as possible (and get the best answers), here's the basic structure you'd generally want to use whenever you are creating a prompt: 

  • Specify the action you want to perform (it could be to edit, write or critique)
  • Follow that up by telling ChatGPT what format you want it to output (JSON, JavaScript, Python, etc.).
  • Specify any conditions and parameters to apply.
  • Add a role or style (this is optional).

Here's an example of a query that contains all of the parts specified above:

1
// Write a function in JavaScript that takes in a string,

2
// then returns the first three and last three characters.

3
// The function should not exceed four lines of code

4
// Use best coding practices

So the action here is to write a function that returns the first and last three characters from a string. The format we want it to return is JavaScript. The condition is that we want it to take no more than three lines. The style here is to use best coding practices.

This is what ChatGPT spits out:

1
function getFirstAndLastThreeCharacters(str) {
2
  const firstThree = str.slice(0, 3);
3
  const lastThree = str.slice(-3);
4
  return `${firstThree}${lastThree}`;
5
}

The actual screenshot is as follows.

Screenshot of function generated by ChatGPTScreenshot of function generated by ChatGPTScreenshot of function generated by ChatGPT
Screenshot of function generated by ChatGPT

Because we were specific in what we asked it for in our prompt, this is a lot more nuanced and specific than it would have been if we'd asked something more generic.

Another great thing about generating code with ChatGPT is that it explains the code. This is super helpful if you're new to programming or don't understand the generated code.

If you're not satisfied with the answer, click the "regenerate" button to generate a different answer. You can also modify your prompt and make it more specific if it helps.

Assign a Tone, Style, or Audience

Often you might be generating code for a specific audience, such as beginners (this is common if you're writing a code-related tutorial). Perhaps you want to generate code that adheres to a specific coding style or convention (e.g. ECMAScript or TypeScript).

In such cases, you need to inform ChatGPT of the style and tone to adopt or the audience to write for. To do this, you'd typically add the following statement to your prompt: "Write in X tone", "write in X language", or "write for X audience".

Here's an example of a query that tells ChatGPT what language to adhere to when generating the code:

1
// Write an infinite loop in JavaScript strictly in ES6 language

This is going to be the output:

1
const infiniteLoop = () => {
2
  while (true) {
3
    // Your code here

4
  }
5
};

Rather than using a regular function, ChatGPT used the ES6 arrow function syntax (() =>) to define the infiniteLoop function, as per our request. You can do the same for other programming languages, libraries, and frameworks.

Bring in the Experts

If you're still new to programming, ChatGPT can play the role of an expert for you. You can ask it to review your code and offer feedback on how to improve it. The prompt you'd use is: You are a (role). Do (action)

For example:

1
// You are an expert JavaScript developer. 

2
// Review my code and give me feedback on how I 

3
// can improve it and make it more concise

Beneath the query, you'll then paste in the code you want ChatGPT to review and click Enter. In return, ChatGPT will review your code and offer feedback on how to improve it.

I asked ChatGPT to review my function for checking whether a string is a palindrome or not. ChatGPT gave me an improved version of my code in return:

1
function isPalindrome(string) {
2
  const len = string.length;
3
  for (let i = 0; i < Math.floor(len / 2); i++) {
4
    if (string[i] !== string[len - 1 - i]) {
5
      return false;
6
    }
7
  }
8
  return true;
9
}

It also gave me a few suggestions to improve its readability and conciseness:

Screenshot of suggestions by ChatGPTScreenshot of suggestions by ChatGPTScreenshot of suggestions by ChatGPT
Screenshot of suggestions by ChatGPT

With this feature, you can review any code to make sure it meets best coding standards.

Keep in mind that ChatGPT can generate faulty code. So you need to test-run the code to confirm that it gives the expected output before pushing it to production.

Use ChatGPT to Get Unstuck

As a software developer, you're bound to run into problems during development. Perhaps your code isn't working and you don't know why. Or you're not sure how to create a function that performs a specific task.

The best place to find solutions used to be on forums like Stack Overflow and Reddit. But now you can use ChatGPT to solve any of your coding-related problems.

The best thing about using ChatGPT is that it's instantaneous, and you don't have to browse through articles or solutions to find what you want. Each solution also comes with an in-depth explanation, which is something you may not find with the answers you get from Stack Overflow or Reddit.

Keep Iterating

You probably will not get exactly what you want right out of the gate, but that is expected. Be prepared to ask ChatGPT to rewrite things, regenerate code blocks, or make adjustments to code. Alternatively, you can simply redo your entire prompt and get something completely new from it.

The key here is to have a collaborative conversation with ChatGPT that goes back and forth, instead of just putting in one prompt and expecting one thing and trying again. 

The cool thing about ChatGPT is that you can have a continuous conversation with it, and it will remember your previous interactions. It'll be able to remember the context of other answers that it gave you within a particular chat.

Conclusion

The key to using ChatGPT effectively is producing well-crafted prompts. Your prompts need to be specific, concise, and as detailed as possible. It should contain an action, the output format, one or more conditions, and a role or style to use (this is optional).

ChatGPT can not only generate code, but also review your own code for errors and provide feedback on how to improve it. When used correctly, ChatGPT can help smoothen the process of developing applications. But if you want an AI tool specifically tailored for programming, check out GitHub Copilot

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.