Redsauce's software and cybersecurity blog

How to write JavaScript with ChatGPT without the headache

Posted by Héctor Sisternas

{1570}

Since some time ago, my day-to-day at Redsauce has involved creating applications and tackling code challenges, both for internal use and for clients.


Back when I started, my tech stack barely included HTML and Bootstrap. But after the arrival of ChatGPT a few years ago, I felt like Spiderman after the spider bite. I had superpowers.


That was the beginning of my journey through various tools, learning the most effective and straightforward ways to ask the AI for help, so it would understand me and deliver exactly what I wanted.


Now, writing JavaScript with AI assistance is no walk in the park: you have to be careful with validations and meeting performance standards—especially if your project needs to integrate with other systems. And as with any kind of development, having someone review your code is always a smart move—pair programming is still one of the best ways to make sure everything runs smoothly.


I'm still not as sharp as my fellow developers, but over time—and after coding this very blog you're reading (yep, this is not a WordPress) and a few other things—I think I can share some tips on how to write JavaScript with a little help from ChatGPT.


And since nothing beats a good example, how about we try adding a button to your website to switch between light mode and dark mode?

Choose your tool

It feels like a new AI drops every two weeks, stronger, smarter, and more feature-packed than the last. I'm not saying you should ignore all the new stuff out there—far from it. My advice: pick one tool you trust for the long run. Stick with the one that’s steadily adding features and, as of today (we’ll see next month), includes reasoning models.


Ever started something by organizing everything down to the last detail, only to end up procrastinating on actually starting? Same deal here. There’s always going to be something new to try, but it’s better to begin with what you know and get good at it. You can always upgrade later if needed. My recommendation: stretch the budget and get the €20/month ChatGPT subscription—you won’t regret it.

Master your tool

You're going to use it—a lot. And the more you do, the better you'll understand its quirks. You'll start noticing when its responses start blending with previous ones, when it loses track of what you're saying, or when it needs you to repeat or rephrase things.


Kind of like when your friend or partner says, "Wait, wait, I’m lost—start over."


After months of trial and error with ChatGPT, I can almost tell the exact moment when it’s better to open a new chat and start fresh rather than continue down a confusing thread.

Learn to write prompts

Seriously, it’s way easier than you think—and it's getting even easier. With memory and reasoning models, you have to feed it less and less context. Still, I stick to a formula that works like a charm:


[persona] + [context] + [task] + [example] + [format] + [tone]


Let me break down the key parts I’ve found especially useful when writing JavaScript with ChatGPT:

  1. Give solid [context]. Define what “success” looks like—what would make the answer perfect. Mention your environment and limitations. The more details you give upfront, the easier it’ll be to follow up later.

  2. Give an [example]. This is huge. Doesn’t matter if it’s a screenshot, StackOverflow snippet, or a crayon drawing—examples say more than a thousand words.

  3. Define the [format]. Do you want the script inline? Say it. Want the variables named “pepito”? Say it. Want to replace a specific piece of your code? SAY IT.

For our example:

  • [persona]: Act like a front-end developer with experience in color themes and usability.

  • [context]: I’m building a simple website with HTML and a CSS file with two classes: .light-mode and .dark-mode. I want to switch between them with a button.

  • [task]: Write the JavaScript that toggles these classes when the button is clicked.

  • [example]: I have an index.html with a <button id="theme-toggle">Switch theme</button> and a <div id="contenido">Sample content</div>.

  • [format]: Just give me the JavaScript part, with step-by-step comments.

  • [tone]: Clear and beginner-friendly.

Pro tip for prompts

If your prompt sounds clunky and you can’t be bothered to clean it up, just add this at the end:

Ask me 5 questions that would help you improve your response.

Let’s improve that JavaScript

Now that you know how to write prompts, your goal is to get working code. Here’s how to make that happen, step by step:

1. Start with a clear idea

Idea: I want a button that switches the class on the body (or main container) from .light-mode to .dark-mode and back.


Try to explain it like you would to a friend—or a rubber duck. The shorter and clearer your explanation, the closer it is to a great prompt.

I’ll have a body with the default class .light-mode. When I click the button, I want the body to switch to .dark-mode. If it’s already in .dark-mode, it should go back to .light-mode.

2. Split your code into clear sections

That way, you can add functionality piece by piece without ending up with spaghetti code that’s impossible to debug.


HTML:

  • A button to toggle the theme

  • Content that changes style based on the theme

CSS:

  • .light-mode and .dark-mode classes with respective styles (background, text color, etc.)

JavaScript:

  • A click event on the button

  • A function that toggles the theme classes

Extract the part of your code where you need help

Say your index.html looks something like this (you’d share this with ChatGPT for context):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic Theme</title>
<link rel="stylesheet" href="styles.css">
</head>
<body class="light-mode">
<button id="theme-toggle">Cambiar Tema</button>
<div id="contenido">
<h1>My web page</h1>
<p>This is a text that will change color depending on the theme.</p>
</div>
<script src="script.js"></script>
</body>
</html>

And your styles.css might be something like:

.light-mode {
background-color: white;
color: black;
}

.dark-mode {
background-color: black;
color: white;
}

Ask ChatGPT to write the JavaScript

Once you've explained your setup to ChatGPT—what your HTML and CSS look like—you can now ask it to generate the JavaScript that does the toggle between light and dark mode. Here's an example of what ChatGPT might return:

// 1. Select the button
const themeToggleBtn = document.getElementById('theme-toggle');

// 2. Listen for click event
themeToggleBtn.addEventListener('click', () => {
// 3. Select the body (or the main container you want to change)
const bodyElement = document.body;

// 4. Toggle between light and dark mode
if (bodyElement.classList.contains('light-mode')) {
bodyElement.classList.remove('light-mode');
bodyElement.classList.add('dark-mode');
} else {
bodyElement.classList.remove('dark-mode');
bodyElement.classList.add('light-mode');
}
});

This is a simple and functional solution that toggles the class based on the current state.

If it fails, add logs

If it’s not working (maybe your script.js isn’t linked right or your button ID is wrong), ask ChatGPT to add logs so you can debug:

console.log('Button loaded:', themeToggleBtn);

themeToggleBtn.addEventListener('click', () => {
console.log('Button clicked!');
// ...
});

These logs will show you in the browser console if the elements are being selected correctly and if the event is firing.

Screenshots and error explanations

If it's still not working, send a screenshot of your console or explain the error message:

When I click the button, I get: Cannot read property 'addEventListener' of null.

And ChatGPT will say:

Check that <script src="script.js"></script> is placed after the button in your HTML. Also, make sure the ID matches exactly.

Iterate until it’s right

Once your theme toggle works, you can ask ChatGPT for more refinements:

Make the button text switch to “Dark Theme” or “Light Theme” depending on the current state.

Save the user’s preference in localStorage so the theme persists on reload.

Bit by bit, you'll polish the example, with increasingly specific prompts. You’ll need some patience and curiosity—think of it as solving small puzzles and slowly putting the pieces together.


Every project, feature or functionality is its own world, so there’s no one-size-fits-all approach. Still, I hope these tips spark some ideas to help you unlock the potential of this tool.

About us

You have reached the blog of Redsauce, a team of experts in QA and software development. Here we will talk about agile testing, automation, programming, cybersecurity… Welcome!