A comprehensive cheatsheet for ChatGPT

Generative AI tools like OpenAI’s ChatGPT and GitHub Copilot expand the frontiers of software development. They provide intelligent virtual assistants to help you enhance your code and streamline your development workflows.

With the right prompts, you can use ChatGPT to improve your development processes. This article will expand your prompt-engineering skills for ChatGPT with a few simple tricks.

Quick reference for enhancing code with ChatGPT

Although ChatGPT is a powerful programming assistant, it has certain limitations. For instance, the model doesn’t understand code or programming like a human does. It can only generate responses based on the patterns it’s learned. Consequently, it may provide plausible but ultimately unfounded answers.

ChatGPT’s knowledge is also static, with a cutoff date of September 2021. This limitation means it can’t account for any updates or advances in programming languages or frameworks that emerged after that date. It might also struggle to understand complex, domain-specific programming requirements.

These constraints are why it’s crucial to use ChatGPT responsibly. While it’s a great tool to aid the development process, it’s neither a definitive source of truth nor a replacement for human input. Developers must thoroughly vet and test any code or solutions it provides, using their expertise to ensure the output’s accuracy and usefulness.

Let’s find out how ChatGPT can complement your development workflow.

Generate a code snippet

ChatGPT provides a unique way to generate code snippets across multiple programming languages. Just input your request and ChatGPT will output the appropriate code. This feature is great for quick prototyping and learning new programming languages.

Simply provide a few contextual examples:

Example input:

Write a JavaScript function to reverse a string

Output:

function reverseString(string) { 
return string.split("").reverse().join("");
}

Then, ask for an explanation of the code it just created:

Example Input:

Explain the reverseString function

Output:

"The function reverseString takes a string as input and uses three main steps to return the reversed string. First, it uses the split("") function to turn the string into an array of characters. Then, the reverse() function is used to reverse the order of the elements in the array. Finally, join("") is used to combine the array elements back into a single string."

You can also use ChatGPT to generate code for more specific programming tasks or request it to use specific technologies. For example, you can prompt the model to:

  • Implement event listeners in JavaScript.
  • Develop an Express.js server.
  • Create a promise chain in JavaScript.

You can also use ChatGPT to generate multiple versions of the same code snippet and explore different implementation methods. Just tailor your questions appropriately and let ChatGPT handle the rest.

Example input:

Write different ways to declare a function in JavaScript

Output:

// Method 1: Function Declaration 
function add1(a, b) {
return a + b;
}

// Method 2: Function Expression
const add2 = function(a, b) {
return a + b;
}

// Method 3: Arrow Function
const add3 = (a, b) => a + b;

This approach can help you adopt a more comprehensive and flexible approach to coding. You can also learn new coding techniques and styles to apply to future projects.

Synergy with tools like GitHub Copilot

ChatGPT can combine with other development tools to enhance overall coding efficiency and productivity.

One such tool is GitHub Copilot, which works directly in your integrated development environment (IDE) to suggest code—based on the context of your current work—as you type.

However, GitHub Copilot only provides limited content for the code it creates and can’t answer specific questions. A more nuanced and conversational AI assistant like ChatGPT works better. ChatGPT can debug your code and help you understand why the coding problem occurred in the first place.

For example, let’s say you use Visual Studio Code with GitHub Copilot enabled. You accept a suggestion from Copilot’s auto-complete feature but mistakenly hit the closing bracket key. This action introduces a syntax error in your code:

for(let i = 0; i <= 10; i++]) { 

console.log(i);

}

Your IDE might highlight the extra bracket after i++ as a syntax error. If you need further clarity, you can present the code to ChatGPT and ask, “Are there any syntax errors in this code?” ChatGPT will then provide a more detailed explanation of the syntax error and the corrected code.

Output:

It appears there is an extra closing bracket after i++. In JavaScript, for loop syntax doesn't require a closing bracket.

Here is the corrected code:

for(let i = 0; i <= 10; i++) { 

console.log(i);

}

You can also ask ChatGPT to explain Copilot’s suggestions, even if the code works perfectly. These insights can illuminate how the code works or why Copilot made certain decisions.

Explaining code is now an experimental feature in the GitHub Copilot Labs extension for Visual Studio Code. This allows developers to view ChatGPT-powered code explanations directly from the IDE. Instead of swapping out, you can embed a basic version of this functionality in the IDE to provide input to ChatGPT.

Together, GitHub Copilot and ChatGPT create an enhanced development environment. CoPilot provides real- time code completion, quick error detection, and automated pair programming, while you can use ChatGPT for in-depth explanations. When used effectively, this combination can make your coding journey smoother and more efficient.

Debugging assistance

ChatGPT can spot syntax errors and assist with more intricate logical or semantic errors that cause bugs in your program. ChatGPT pinpoints such errors and provides potential solutions, which significantly speeds up the debugging process and fosters a deeper understanding of the code’s logic.

Consider the following example using an asynchronous function in JavaScript:

Example input:

function fetchData() { 
return new Promise(resolve => {
setTimeout(() => resolve("Data fetched!"), 2000);
});
}

console.log(fetchData());

Why does this JavaScript function not print "Data fetched!" to the console?

Output:

"The function fetchData() returns a Promise object because it's an asynchronous function. This Promise object is immediately logged to the console before it has a chance to resolve to the string "Data fetched!". If you want to log the resolved value of the Promise, you need to wait for the Promise to resolve using then() or an async/await structure. Here's a corrected version using .then():

function fetchData() { 
return new Promise(resolve => {
setTimeout(() => resolve("Data fetched!"), 2000);
});
}

fetchData().then(data => console.log(data))

In this revised code, fetchData().then(data => console.log(data)); waits for the Promise from fetchData() to resolve, then logs the resolved data, which will be the string "Data fetched!".

Performance optimization suggestions

Performance optimization is a nuanced area of software development, often necessitating a deep understanding of the language, tools, and specifics of the code. ChatGPT can provide insightful advice and specific recommendations for various code performance issues.

Prompt ChatGPT with specific optimization strategies and it can implement them for you. Or you can simply drop some code into it with a request for better performance and see what it recommends.

Example input:

How can I optimize this SQL query for better performance?

SELECT * FROM Employees  
INNER JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID
WHERE Employees.Age > 30;

Output:

"An effective way to optimize this SQL query could be limiting the amount of data retrieved. The 'SELECT *' statement retrieves every column from the table, which can be quite slow if the tables have many columns. If you only need specific columns, specify them instead of using '*'.

Also, using indexing on the columns involved in the join and WHERE clause (Employees.DepartmentID and Employees.Age in this case) can help speed up this query. Here's an optimized version:

SELECT Employees.Name, Departments.DepartmentName 
FROM Employees
USE INDEX (DepartmentID, Age)
INNER JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID
WHERE Employees.Age > 30;"

There’s no single, objective goal for optimization. For instance, if developers optimize for performance, they might sacrifice other important factors like maintainability to pursue better benchmark metrics. Consequently, results vary if developers request ChatGPT to “optimize” a program.

You can ask for generalized recommendations, but telling ChatGPT exactly how you’d like to optimize your code is more effective. You can paste in a code snippet alongside specific instructions for optimization. Some examples include:

  • “Can I modify this JavaScript function for non-blocking or asynchronous execution?”: Ideal for handling JavaScript functions that perform heavy computations or input/output (I/O) operations. These types of functions can benefit from asynchronicity to avoid blocking the event loop.
  • “What’s a better way to parallelize this computation-heavy C++ code?”: Useful when dealing with C++ code that you can speed up through multi-threading or parallel processing capabilities.
  • “Is there a more efficient algorithm for sorting this large list?”: Useful when you want to improve the time complexity of the sorting algorithm for large data sets

In each prompt, the key is to provide as much detail as possible about the problem, along with the related code snippet. ChatGPT provides the most helpful and relevant responses when it clearly understands your prompt.

Implementing best practices

ChatGPT isn’t just an AI tool that generates code or spots errors. It’s also an on-demand tutor for coding best practices. ChatGPT offers guidance on efficient and maintainable coding techniques and assists developers in writing clean, robust, and reliable code. Using ChatGPT this way is a more effective form of search, saving developers time and providing precise, actionable results in natural language.

One primary area where ChatGPT excels is in providing best practices for specific tasks. Let’s consider a few strategies to extract such insights from ChatGPT:

  • Ask about general best practices: A question could be as simple as, “What are the best practices for coding in Python?” or “What are some best practices for writing asynchronous JavaScript code?” ChatGPT can return a list of high-level best practices that the community generally accepts.
  • Ask about task-specific best practices: If you’re working on a specific task or feature, you can ask ChatGPT for related best practices. For example, “What are the best practices for error handling in Node.js applications?” or “What is the recommended way to implement state management in a React application?”
  • Ask about language-specific or library-specific best practices: You can ask for best practices related to particular programming languages or libraries. For instance, “What are best practices for memory management in C++?” or “What are some best practices for using the ReactJS library?”
  • Ask about Design Pattern Recommendations: Besides programming languages and libraries, software design patterns are critical to build scalable and maintainable software. You can ask ChatGPT about which design pattern best fits a particular scenario. For instance, you might ask, “Which design pattern should I use to manage database connections in a Java application?” or “What’s an appropriate design pattern to handle complex user interactions in a React application?”

Here’s an example of how ChatGPT provides actionable results.

Example input:

What are some best practices for asynchronous programming in JavaScript?

Output:

"Asynchronous programming is a key part of JavaScript, especially for operations like API calls, database operations, or file reading and writing. Here are some best practices to follow:

  • Promises and Async/Await: Use Promises and Async/Await for handling asynchronous operations. This helps avoid callback hell and makes your code cleaner and easier to understand.
  • Proper Closure: Be mindful of closures in asynchronous code to avoid issues related to scope and memory leaks.
  • [etc. etc.]"

You can enhance your code directly with these ChatGPT insights. It's a mentor that can provide guidance and best practices based on vast accumulated knowledge.

Refactor code

Code refactoring is a critical aspect of the software development process. It improves software design, structure, and implementation without altering its functionality. It can make your code more readable, maintainable, and efficient. When you leverage ChatGPT for code refactoring, it identifies alternative implementations and potential areas for improvement.

To refactor effectively with ChatGPT, consider the following strategies:

  • Ask for general refactoring: If you’re unsure where to start, ask ChatGPT to refactor a code block. For instance, “Can you refactor this JavaScript function for better readability?”
  • Specify the refactoring technique: If you seek a specific type of refactoring, indicate this in your query. For example, “Refactor this JavaScript code to use the ‘map’ method instead of a ‘for’ loop.”
  • Request refactoring to a specific coding style or paradigm: If you adhere to certain coding styles or paradigms (like functional programming), request ChatGPT to refactor the code accordingly. For example, “Refactor this JavaScript code to follow functional programming principles.”
  • Use to learn new language features: If a language you use has been updated with new features since you wrote your project, ChatGPT can refactor your code to use them. This helps you learn the new features swiftly. However, remember that ChatGPT’s training data does not surpass September 2021, so it won’t suggest anything too cutting edge.
  • Translate to a different programming language: ChatGPT can quickly swap code from one programming language to the next. While the transition probably won’t be seamless for complex projects, this feature is helpful to port simple applications. When you learn a new programming language, you can more easily understand the syntax and semantics of the new language as ChatGPT examines a translated example of well-understood code from another language.

Let’s look at an example of refactoring with ChatGPT.

Example input:

Refactor this JavaScript function to use the 'reduce' method and a ternary operator.


// Original function using for loop and if statement
function calculateTotalPrice(cart) {
let total = 0;
for(let i = 0; i < cart.length; i++) {
if(cart[i].onSale) {
total += cart[i].price * 0.8;
} else {
total += cart[i].price;
}
}
return total;
}

Output:


// Refactored function using 'reduce' method and ternary operator
function calculateTotalPrice(cart) {
return cart.reduce((total, item) => total + (item.onSale ? item.price * 0.8 : item.price), 0);
}

The refactored function uses the reduce method to condense the array into a single total price value. It uses the ternary operator to check whether each item is on sale. This approach offers a more concise alternative to the if-else statement. The final function is more efficient, easier to read, and demonstrates the power of modern JavaScript methods and operators.

Conclusion

ChatGPT’s capabilities can transform your development processes. Whether you need it to generate code snippets, detect syntax errors, assist in debugging, offer performance optimization strategies, and refactor code, ChatGPT is an invaluable tool in any developer’s arsenal.

But while ChatGPT is powerful, it isn’t perfect. Always pair its suggestions with your expertise and manual review. Explore, experiment, and make the most of this advanced AI model to produce higher quality software and enjoy a streamlined development experience.

Was this article helpful?

Related Articles

Write For Us

Write for Site24x7 is a special writing program that supports writers who create content for Site24x7 "Learn" portal. Get paid for your writing.

Write For Us

Write for Site24x7 is a special writing program that supports writers who create content for Site24x7 “Learn” portal. Get paid for your writing.

Apply Now
Write For Us