How to use ChatGPT as a web developer

Aleksandar Radeski
Codeart
Published in
15 min readNov 22, 2023

In the realm of Artificial Intelligence, there’s a new sheriff deputy in town who has been taking the spotlight for the past year. Meet ChatGPT, armed with an extensive knowledge base gathered from diverse sources, ranging from reliable academic research papers and original software documentation to content from more questionable origins like news articles, Wikipedia, and even social media conversations.

As a pioneering force in the public domain of AI, ChatGPT has made headlines for everything from apocalyptic doomsday prophecies to creative and revolutionary use cases, including crafting personalized rap songs for your colleagues. On the surface, it impresses as an exceptionally knowledgeable chatbot with unparalleled conversational skills and contextual understanding. What distinguishes this AI is its meticulous training through supervised machine learning, tapping into extensive real-world data to refine its knowledge and adhere to ethical guidelines.

However, before we relinquish the reins to our artificial overlords, it’s essential to acknowledge the limitations, drawbacks, and potential pitfalls. Even though ChatGPT is exceptionally knowledgeable, no software yet can supplant the human attributes of critical thinking, creativity, emotional intelligence, and common sense.

In this article, we’ll explore how you, as a Sheriff in Web Development County, can harness the power of your AI Deputy for assistance, guidance, and an extra set of eyes when needed.

1. Code conversion, summarization and explanation

As web developers, oftentimes, we find ourselves looking at an unreadable stream of characters and are expected to make something of it. Whether it be a new language, new framework or compiled code that is only meant to be read by a machine and not a person. It can even be code that we work with every day but is a devil to interpret such as regex patterns, complex SQL queries or even ordinary legacy code.

Imagine you’re assigned to a new backend project with a complex database with many tables and relationships. At first glance the SQL queries will definitely look scary and your next step is to chop them up piece by piece and decipher the bigger picture. We will give our artificial assistant a try at deciphering a query and inferring its context to us.

As an example we’ll use the above SQL query which is nested a couple of times and it poses a challenge to interpret at first glance.

As a prompt we’ll use the following:

Can you help me by summarizing the action, inferring the context and drawing a minimal example of the tables used in the following query:{QUERY_HERE}

As a response, I get a lot of information, divided into blocks according to question context, just as I requested, as it tries to extract everything it can based on the input provided. Here’s the first block in the response:

Amazing. The first block takes a guess based on the names of the tables and column names, and it does so correctly. This is already enough to familiarize me with the query in question, its action, and a guess at the bigger picture.

The next two blocks are code examples of the schema for the tables based only on the initially provided query:

Again, with a bullseye. Keep in mind these are not ALL of the tables and fields in our database, nor are the types of values definitely correct as some of them can be null or completely omitted. These are the ones that can be inferred from the query we supplied, but since it’s a bigger query dealing with multiple tables and values, this information is quite great and it paints a clearer picture of our task.

Our next block goes even further to fill the above tables with sample mock data based on the types we inferred in our previous block:

As a finishing touch, it describes the result our query returns and some more context on the usage and details of the query itself.

From the received information, we can understand that the purpose of the query is to find the name of the driver that last handled the package in question.

This is a solid example of how ChatGPT can be used with long, complex, and barely readable code as a prompt and provide summarization, explanation, and even infer context from names used for the data fields. Even though we are a few steps closer to understanding our task at hand, it is very important to keep in mind that the information we provided for our prompt is limited as it does not encapsulate the whole of our database or fields, and thus, the results are incomplete and not strictly defined themselves, and we should not base our next steps on incomplete information going forward.

Next up, we have some regex wizardry. Regular Expressions find their usage in the front-end and back-end, for mostly validation purposes. Validation is a very important aspect of every piece of software, especially when interacting with end users. But the visual appeal of regex patterns is non-existent.

Have a look at this simple regex pattern that is used for simple password validation:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W).{8,16}$

This abomination is serving a great purpose, is mandatory, and requires extensive knowledge and analysis to create or even understand it, as it’s as far away from user-friendly as possible. Let’s put our assistant to the task.

We’ll start by asking it for information on this regex pattern using the following prompt:

What does this regex pattern match and where could it be used, try to infer context from it: ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W).{8,16}$

A winner again. We have a detailed explanation of what each part of the regex does, we have a summary for the pattern as a whole and we have a valid guess about where it could be used. As always, the second step is to verify and question the results ourselves.

We head over to an online regex editor and write some tests for our query, so we can make sure we get what we ask for.

Attaining a wizard certificate in regex patterns might take a while and some would argue that the reward is not worth the investment, a tool that can explain and generate such patterns would prove an invaluable asset for us.

A developer often has to deal with things he knows nothing about, so our daily routine includes googling for answers on topics we’ve barely touched. We can structure a prompt to reduce hours of googling to a few minutes with a detailed and instructive prompt.

In this next example, we’ll go over code conversion, we have a TypeScript function used to generate a more user-friendly string as a way to notify a user of a Date Range, the function is the following:

Let’s say we need a block of Python code that has this functionality, but we’ve never touched Python code, let alone write a full function with it.

We structure the following prompt:

Can you convert the following TypeScript function into Python :`{FUNCTION}`

We get the following response:

Seems about right, but as a purely JavaScript developer that f” part in the return value is making me uneasy, I’ve never encountered such a syntax before, let’s go further and ask our assistant for an explanation.

What does the f” mean in this python function?

The response we get is the following:

Now this is something I can work with, the answer is template literals. As a bonus I get an explanation of how template literals are used in Python and how they are implemented in the context of the function I provided.

This concludes our section about using ChatGPT for code conversion, explanation and summarization. From inferring context based on data field names in complex SQL queries, generating and summarizing provided regex patterns down to translating code into another language, as long as we prompt our AI colleague with all the specifics and double check the results, we can drastically ease our experience as a developer when working in unfamiliar territories.

2. Commands, Syntax & Concept recall

Remembering concise syntax or commands should not be a burden on a developer’s mind. The main takeoff from any mastered skill should be the concept, use cases, implementation and limitations. With that in mind, even for a simple developer position, the technologies and syntax can prove to be of an overwhelmingly large nature to remember. On top of that, we have to keep in mind the differences between versions that change and update their syntax.

Managing libraries in a project requires careful consideration of their version-specific syntax and methodologies. Even for experienced developers, navigating between different versions can be challenging, as syntax and features may vary. This is particularly evident when working on older projects. Similar challenges arise in everyday tasks, such as recalling specific Git commands or remembering code details like linking a CSS file to an HTML file.

This is a field which our deputy could provide assistance in. Utilizing the chatbot to recall what’s the proper command/syntax for a specific action is a common practice. Here are some example prompts that come in handy at a moment’s notice:

-> What git command do I use to compare two commits?

-> How do I define and use state in React class components?

-> What’s the syntax for a JavaScript Promise and can you explain the concept?

-> What does “git rebase” do?

-> What SQL statement is used to insert data to a specific table?

-> What is the syntax for the Redis Geospatial data structure?

These prompts not only provided concise answers to syntax or commands but also offered comprehensive refreshers, complete with implementation examples and reminders of potential mistakes. It’s important to note that this approach is best suited for revisiting familiar commands, concepts, and syntax. When dealing with entirely new concepts or tools, it’s advisable to begin with official sources like manuals and documentation.

3. Debugging

The first step of using ChatGPT for debugging purposes is carefully crafting a prompt of all the details that are related to the issue you are experiencing, as well as any error messages, unwanted side-effects or behavior you encounter. While this approach is optimal, we do not always encounter errors with a detailed explanation of what and where exactly went wrong.

Before handing the whole project to our deputy, here are some key steps you can take that will strengthen the chances of ChatGPT providing a valuable response:

  • Isolate — Try to isolate the problem or at least narrow it down to an individual chunk of code, be it a page, component, or controller, depending on the project and methodologies used
  • Feedback — Collect any error messages, console prompts, or IDE indicators of where the error occurred and include them in the prompt along with any code, clues or behavior description
  • Origin — Include the erroneous code AND the error messages. The more information you provide, the easier it’s job will be and greater the success rate
  • Trial & Error — It could prove to be helpful and narrow the response and possible solutions if you include your previous attempts at solving the error. Something along the lines of “I already tried restarting the router and running the troubleshooter with no different results”. If the problem could be caused by a wider range of factors, this kind of input could go a long way of narrowing down ChatGPT’s response and saving you some time
  • Elaborate — If there are no written or detailed errors, try providing an explanation of the expected and received behavior of the specific subject. Remember to include details about the environment the subject is executed in and other external factors that might limit or alter the functionality of the subject
  • Define end goal — Make your end goal clear for the supplied code. A component or function could be working, but it could satisfy a different purpose rather than your intended one and a miscommunication could occur

With these guidelines in mind, let’s give it a go with an example. This example is in a big codebase with millions of lines in it and for the time being everything is functional and operating as it should. We’ll first break the code by inserting this line

This is a simplified version of a common occurrence, for example trying to filter data received from an API before it’s finished fetching.

We’ll sneak this code inside a random component that could be a few thousand lines long, rendered and used multiple times across our application. This should crash our application and the error stack should pop up in our console.

Even though we can get a pretty clear hint about the origin and type of the error just from the first two lines from the error stack, stack traces can usually get wild and incomprehensible. Let’s see what our assistant has to say about it. We’ll give it a shot with a rushed simple prompt and just swing it as fast as we can:

I’m getting an error. I’m working on a React application, can you help me? This is the error I get: {ABOVE_ERROR}

This is the response:

Clear and precise, this debugging approach effectively identifies the error’s origin and type, providing multiple solutions. This method is also valuable when working with various libraries, each with its unique error messages — some user-friendly, others requiring external research. While ChatGPT excels in recognizing popular libraries and pinpointing issues, unfamiliar ones pose a challenge.

This approach is highly dependent on the popularity and usage of the said product, as well as its ecosystem coverage. An example is if a library or a library problem has good coverage from Google or StackOverflow, the bigger the chance of ChatGPT having heard of the problem and has solutions or alternatives to it.

4. Refactor, Feedback & Brainstorming

Refactoring old code is a virtue of great developers. But it often grows into a bigger challenge and it requires great attention and focus from the developer as a number of things can go wrong while attempting to improve something that already works. Refactors are also always better in groups or pairs, when certain aspects can be discussed and agreed upon as a better approach.

We’ll put our assistant on the spot and see how good his teamwork is as we try to refactor some code and ask for its feedback and maybe some ideas for improvements.

For starters, we have this utility function that we use to extract the file extension from a full file name. Written in TypeScript, nothing too fancy, its string operations and our function has fulfilled its duty for quite some time, but let’s see if we missed something or if we can do some improvements.

Our prompt will be a simple one, on to the point. We include the language, usage, expected behavior and the feedback we want from our assistant:

I have a function written in TypeScript that is used to extract only the file extension from a full file name. Can you take a look, analyze it and suggest improvements for better handling or covering some missing scenarios? Here’s the code:{ABOVE_FUNCTION}

Response:

Both of these are insightful remarks. It’s easy to forget a simple and valid edge case like this one when working with strings or user input and our assistant might’ve saved us from a potential feature malfunction down the road.

This next example goes a step further and despite improvements and feedback, we request some brainstorming and ideas for improving a function by extending the functionality and implementing wider range of features.

This utility function is used for client-side file download, it receives a data blob and file name as parameters and all the magic of initiating a file download happens inside, let’s have a look.

The prompt:

Can you give me a summary, some feedback and suggestions for improvement for the following typescript function? {ABOVE_FUNCTION}

The response, as requested, comes in three blocks, containing the summary, feedback and suggestions for improvement. We’ll go over them one by one.

Pretty straightforward, the comments in the code prove to help ChatGPT with contextualizing code and lower the chance of misunderstandings.

Valid. Valid. Valid.

After writing code, it’s a common practice to take a last objective look at it and try to find inconsistencies and shortcomings and correct them. But we’re always subjected to tunnel vision and finding fault in someone else’s code is MUCH easier and more natural than noticing it in ours.

Lets see our deputy’s ideas for our function improvement.

Even though our code was devised in smaller code chunks and each chunk commented, our assistant seems to have forgotten about them or glitched out a bit, so its first suggestion is invalid.

The next three remarks are on point and drastically improve our consistency and safety. At the bottom we have a typed example of all the suggestions applied.

With our next prompt we continue the conversation going for the topic at hand — the blob download utility function. This time we ask for a brainstorm.

Can you also brainstorm some ideas for the function so I can make it more reusable or have richer features?

This is my favorite part. It borders creativity and innovation. We’re handing over a default pizza recipe and asking for ideas on different flavors and recipes. Here’s the response:

In both cases, my deputy had some valid arguments on how to improve my code and pointed out some cases which I missed and as a developer this experience proved fruitful and fulfilled the expectations i have from a partner.

5. Limitations, Drawbacks & Pitfalls

Despite the otherworldly and futuristic air around our sidekick, its imperfections and shortcomings are what ground the whole concept to reality. Constant awareness and understanding of these drawbacks are a crucial part of finding success and value in ChatGPT’s usage. We’ve dropped hints and tips about the pitfalls throughout this article and now we’ll list them side-by-side.

  • Lack of Context — ChatGPT heavily relies on the context provided in the prompt. If the prompt is vague or unclear, the response may not be accurate or helpful. Developers need to formulate precise, detailed and well structured queries to get the desired results
  • Incomplete — ChatGPT’s responses are generated based on the data it has been trained on. If it lacks exposure to specific topics or the latest developments in the ecosystem, it may not provide up-to-date information and solutions
  • Overdependence — Relying too heavily on ChatGPT can hinder developers from honing their problem-solving skills and overall personal progress in the field. It’s essential to use ChatGPT as a supplementary tool, rather than a replacement for personal expertise or lack of it.
  • Bias, Misinformation & Ethical Concerns — As we’ve already mentioned a couple of times, ChatGPT is trained on data provided and made by humans and as a certainty we know that humans are prone to bias, misinformation and are in general an unreliable source of truth. This human trait we’ve passed down to our creation and every critical or ethical information we receive as response must be verified by an authoritative source.
  • No creativity or intuition — Every response is based on patterns it has learned from and paths already walked by a real entity, so ChatGPT is incapable of novelty, innovative ideas or outside the box thinking approach to solutions.

Conclusion

Whispers of AI replacing the human factor as the core necessity in every prospect can be heard at the slight mention of the topic, but the human touch still reigns supreme. Nonetheless AI and its pioneer in the public domain, ChatGPT, have proven as a valuable asset in a developers toolbox from more than a single angle. Its exceptional conversational prowess, knowledge base and sometimes even the deficit of human characteristics come on top with flying colors for the sidekick position.

While its contributions to our development endeavors are undeniable, lack of acknowledgement to ChatGPT’s aforementioned limitations can have severe consequences and set you on the wrong path further away from your desired destination.

Recognizing the strengths and weaknesses in this symbiotic relationship, we can harness the power of AI while preserving the unique qualities of human expertise. As we continue to innovate in the realm of web development, ChatGPT remains a steadfast ally, supporting our progress and helping us meet the ever-evolving challenges of the digital landscape.

--

--