In just one year, we went from "What's AI?" to companies posting "Prompt Engineer" as a hireable role on their job boards.
To say 2023 wasn't a transformational year in the AI space is an understatement.
While there's a lot of fear-mongering going around these days:
- "AI will replace programmers"
- "Web development is dead"
I'm not a prophet. I can't tell you what things will look like in 10 years, but if I had to put money on it, I'd say these claims are wildly overstated.
Test | Table |
---|---|
With | Values |
I don't think web development is going anywhere. I think web development is changing (as it always has).
And with that change, we as programmers need to learn how to use new tools and work on new problems.
The good news?
That's exactly what a software engineer is—someone who is constantly learning and adapting with changes in technology.
So in this post, I want to share 17 Chat GPT prompts that I have been using in my professional life that will help you be a more effective programmer.
ChatGPT Prompts for Learning to Code
Prompt #1: "Explain this code"
Template
Explain the code below:
```
Place code here
```
Example
GPT Prompt
Explain this code prompt
Prompt
Explain the code below:
```
"use client";
import { useEffect, useState } from "react";
export default function useNavbarVisible() {
const [prevScrollPos, setPrevScrollPos] = useState(0);
const [visible, setVisible] = useState(true);
useEffect(() => {
const handleScroll = () => {
const currentScrollPos = window.pageYOffset;
const isScrollingUp = prevScrollPos > currentScrollPos;
setPrevScrollPos(currentScrollPos);
setVisible(isScrollingUp || currentScrollPos < 10); // Show if at top or scrolling up
};
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, [prevScrollPos]);
return { visible, prevScrollPosition: prevScrollPos };
}
```
Prompt Response
This code defines a custom React hook, useNavbarVisible
, which is used to determine the visibility of a navigation bar (navbar) based on the scroll position of the page. It's a common technique in web development to hide the navbar when scrolling down and show it when scrolling up for a better user experience. Let's break down the code:
"use client";
: This line is likely a project-specific or framework-specific directive, not standard JavaScript or React. It could be indicating that this code is meant to run on the client side.- Imports:
useEffect
anduseState
are imported from React.useEffect
is used for side effects in functional components, anduseState
is for state management.
useNavbarVisible
Function:- This is a custom hook, as indicated by the
use
prefix. Hooks are functions that let you “hook into” React state and lifecycle features from function components.
- This is a custom hook, as indicated by the
- State Management:
prevScrollPos
: A state variable initialized to0
. It stores the previous scroll position.visible
: A boolean state variable initialized totrue
. It determines whether the navbar is visible.
useEffect
Hook:- This hook is used to execute code after the component mounts and after every render when
prevScrollPos
changes. - Inside
useEffect
, a functionhandleScroll
is defined. This function is executed whenever the scroll event is triggered.currentScrollPos
: Gets the current vertical scroll position of the page.isScrollingUp
: A boolean that istrue
if the previous scroll position is greater than the current scroll position, indicating that the user is scrolling up.setPrevScrollPos(currentScrollPos)
: Updates theprevScrollPos
state with the current scroll position.setVisible(isScrollingUp || currentScrollPos < 10)
: Sets thevisible
state. The navbar is visible if the user is scrolling up or if the scroll position is near the top of the page (less than 10 pixels from the top).
window.addEventListener
: Adds an event listener to the window object to listen for scroll events.- The return function from
useEffect
removes the event listener when the component is unmounted or before the next execution of theuseEffect
hook to avoid memory leaks.
- This hook is used to execute code after the component mounts and after every render when
- Return Value:
- The hook returns an object containing the
visible
state and theprevScrollPosition
.
- The hook returns an object containing the
In summary, useNavbarVisible
is a custom hook that toggles the visibility of a navbar based on the user's scroll actions on the page. It shows the navbar when scrolling up or when near the top of the page, and hides it otherwise.
Potential Follow-ups
Here are a few prompts that you might use as a follow-up to this response:
- Can you explain useEffect in more detail?
- What framework uses the "use client" directive?
- Is useNavbarVisible a standard React hook? Where did it come from?
Prompt #2: "Guide me step-by-step"
Template
Can you guide me step by step to learn [technology]? Make this interactive and prompt me as we learn.
Example
GPT Prompt
Step by Step Learning Prompt
Prompt
Can you guide me step by step to learn the PHP programming language? Make this interactive and prompt me as we learn.
Prompt Response
Absolutely, I'd be delighted to guide you through an interactive learning experience in PHP! Let's start from the very beginning and move step by step. I'll prompt you with tasks or questions as we go along. Are you ready to start?
Step 1: Understanding What PHP Is
Task: Could you briefly describe what you understand by PHP and its primary use?
Potential Follow-ups
At this point, ChatGPT will guide you step by step to learn PHP. You'd likely want to follow up with something like:
- I don't know anything about PHP
- I've written basic PHP code before, but don't know much
Prompt #3: "I know XYZ. Help me learn..."
The idea with this prompt is to get a tutorial built specifically for your own skillset. You may be able to find a "Ruby tutorial" online somewhere, but it will be a lot harder to find "Ruby for JavaScript devs" online. That's where ChatGPT comes in handy.
Template
I know [ABC technology]. Can you help me learn [XYZ technology] by incorporating concepts that I already know?
Take me step by step through this and make the learning interactive by prompting me.
Example
GPT Prompt
Learn XYZ with existing knowledge prompt
Prompt
I am an intermediate JavaScript developer. Can you help me learn Ruby by incorporating concepts that I already know?
Take me step by step through this and make the learning interactive by prompting me.
Prompt Response
Absolutely! Let's make this a fun and interactive learning experience. Since you're already familiar with JavaScript, I'll draw parallels to Ruby, highlighting differences and similarities. We'll cover key concepts in steps, and after each explanation, I'll provide a small exercise for you to try. Let's get started!
Step 1: Basic Syntax and Structure
JavaScript:
- You're used to semicolons and curly braces.
- Example:
if (condition) {
// code
}
Ruby:
- No semicolons are needed, and
end
is used to close blocks. - Example:
if condition
# code
end
🏋️♂️ Exercise: Convert the following JavaScript code to Ruby:
if (x > 10) {
console.log("x is greater than 10");
}
Once you've tried this, let me know your answer, and we'll move on to the next concept!
Potential Follow Ups
As you can see, ChatGPT's first response gave a code challenge but forget to teach us how to define a Ruby variable or "print" something to the console. In this case, I'd follow up with the prompt:
GPT Prompt
Ruby follow-up prompt
Prompt
How do I "console.log" in Ruby? Also, don't we need to define the `x` variable first? How do we do that?
Prompt Response
Great questions!
In Ruby, the equivalent of JavaScript's console.log
for outputting to the console is puts
or print
. The puts
method prints the output followed by a newline, while print
does not add a newline.
Regarding variable declaration, in Ruby, you don't need to specify a type when you declare a variable (it's dynamically typed, just like JavaScript). However, unlike JavaScript, there's no need for var
, let
, or const
keywords. You simply assign a value to a variable name.
For example, in JavaScript you might write:
let x = 15;
In Ruby, you would write:
x = 15
🏋️♂️ Exercise: Now, given this information, try converting the JavaScript code you were given into Ruby. Remember, you're checking if x
is greater than 10, and if it is, you're printing a message to the console.
Prompt #4: "What should I learn next?"
One of the most common questions I get from my viewers on YouTube is, "where do I go now?"
I built this site, Full Stack Foundations to help answer that question, but ChatGPT can also be a helpful assistant here. Take these responses as suggestions that you'll research further. Please do not base your entire learning path off a ChatGPT response!
Template
I just finished learning [XYZ Concept]. What are some possible next learning paths if I want to become [dream job]?
Example
GPT Prompt
What do I learn next prompt
Prompt
I just finished learning the basics of HTML, CSS, and JavaScript. What are some possible next learning paths if I want to become a game developer?
Prompt Response
Transitioning from the basics of HTML, CSS, and JavaScript to game development is an exciting journey. Here are some learning paths and key topics you should consider to advance towards becoming a game developer:
- Advanced JavaScript for Game Logic: Since you've learned basic JavaScript, dive deeper into advanced topics like object-oriented programming, canvas API for 2D graphics, and game loops.
- HTML5 Canvas API: Learn to use the Canvas API for drawing 2D graphics on the web. This is crucial for creating visual elements in browser-based games.
- WebGL and Three.js: For 3D game development in the browser, start with WebGL and libraries like Three.js. These are powerful tools for creating and rendering 3D graphics.
- Game Engines: Explore game engines that support JavaScript or have visual scripting, like Phaser.js for 2D games or Unity with C#. Unity is particularly popular in the industry and can be used for both 2D and 3D games.
- C# and Unity: If you choose Unity, learning C# is essential as it's the primary language for Unity game development. Unity offers a robust platform for both indie and professional game development.
- Game Development Fundamentals: Study game design principles, storytelling in games, character development, and user experience. Understanding what makes games fun and engaging is as important as technical skills.
- Mobile Game Development: If you're interested in mobile games, consider learning about frameworks like React Native or tools like Unity, which can deploy games to iOS and Android.
- Math and Physics: Brush up on math and physics concepts, as they are crucial in game mechanics, collision detection, and realistic movement.
- Virtual Reality (VR) and Augmented Reality (AR): These are emerging fields in gaming. Understanding the basics of VR/AR development could open up innovative gaming experiences.
- Build and Share Games: Start building small games and share them online for feedback. Platforms like itch.io are great for indie developers to showcase their work.
- Networking and Multiplayer Concepts: Learn about network programming if you are interested in creating multiplayer games. This includes understanding client-server models and handling real-time data synchronization.
- Portfolio Development: As you create games, build a portfolio to showcase your work. This is crucial for employment or freelance opportunities in the gaming industry.
Remember, game development is a field that requires both creative and technical skills. Continuously create, play, and learn from games to understand what makes them enjoyable and successful. Good luck on your game development journey!
Follow up Prompt
You can browse through the responses and start narrowing things down:
GPT Prompt
Follow up prompt
Prompt
Unity sounds interesting. Can you tell me more about that learning path and what types of games I could create with it?
Prompt Response
Unity is a powerful and versatile game engine that's widely used in the gaming industry, from indie developers to large studios. Here's a detailed look at the learning path for Unity and the types of games you can create with it:
Unity Learning Path
- Introduction to Unity Interface: Start by familiarizing yourself with Unity’s interface, understanding the scene view, game view, hierarchy, project window, and inspector.
- C# Programming for Unity: Unity uses C# as its scripting language. If you're not already familiar with C#, you'll need to learn the basics of this language, focusing on concepts used in game development like variables, control structures, classes, and inheritance.
- Building Scenes: Learn to create and manipulate scenes, which are the foundation of your game. This includes placing objects, setting up environments, and understanding the camera and lighting.
- Game Objects and Prefabs: Understand how to work with game objects and prefabs (pre-fabricated objects) for efficient game design and development.
- Physics and Collision: Dive into Unity’s physics engine to manage game object behaviors, including collision detection, rigidbodies, and the application of forces.
- Scripting Game Mechanics: Apply C# scripts to create game mechanics. This includes player movement, object interactions, game logic, and UI elements.
- Animation and Sound: Learn to integrate animations and sound effects to bring your game to life. Unity supports both 2D and 3D animation.
- AI Programming: For more advanced games, delve into AI programming to control non-player character behavior.
- Optimization Techniques: Understand how to optimize game performance, including managing assets, efficient scripting, and scene loading.
- Build and Deployment: Learn how to build and deploy games to various platforms like PC, mobile devices, and consoles.
- Networking for Multiplayer Games: If interested in multiplayer games, learn about Unity’s networking capabilities to handle multiple players in a game environment.
- Virtual and Augmented Reality: Unity also supports VR and AR development, which you can explore if interested in these cutting-edge technologies.
Types of Games You Can Create with Unity
- 2D Games: Platformers, puzzle games, RPGs, and more. Unity’s tools for 2D development are robust and user-friendly.
- 3D Games: First-person shooters, adventure games, racing games, and simulations. Unity’s 3D engine is powerful and capable of producing high-quality graphics.
- Mobile Games: Unity offers great support for mobile game development, allowing for deployment on both iOS and Android.
- VR and AR Games: Create immersive experiences in virtual or augmented reality. Unity is compatible with major VR/AR hardware.
- Multiplayer Games: From simple turn-based games to complex real-time multiplayer games, Unity’s networking features can handle a wide range of multiplayer formats.
- Educational Games: Develop interactive and educational experiences, leveraging Unity's versatility.
- Simulation Games: Unity’s physics engine allows for realistic simulations, making it suitable for creating simulation games.
Unity's comprehensive suite of tools and its supportive community make it an excellent choice for aspiring game developers. Whether you're interested in indie game development or aiming for a career in a large studio, Unity provides the necessary tools to bring your game ideas to life.
Prompt #5: "Give me a project to build"
Template
I just finished learning [XYZ Concept] and I want to practice my skills. Can you give me a [skill level (beginner, intermediate, advanced)] level project brief and some hints to get me started?
Example
GPT Prompt
Project Prompt
Prompt
I just finished learning HTML, CSS, and JavaScript and I want to practice my skills. Can you give me a beginner-level project briefing and some hints to get me started?
Prompt Response
Congratulations on learning HTML, CSS, and JavaScript! These are fundamental skills for web development. Here's a beginner-level project idea along with some hints to get you started:
Project Brief: Personal Portfolio Website
Objective: Create a personal portfolio website showcasing your skills, projects, and a bit about yourself. This website should be responsive and interactive, utilizing your HTML, CSS, and JavaScript skills.
Key Features:
- Homepage: Introduce yourself with a catchy headline and a brief paragraph. Include a professional photo if you wish.
- About Me Section: Share your journey, skills, and any hobbies or interests.
- Projects Section: Display a gallery of projects you've worked on. Each project can have a thumbnail image, a brief description, and a link to the live project or GitHub repository.
- Contact Section: Include a contact form for visitors to reach out to you. Use JavaScript to validate form inputs (like email format).
- Responsive Design: Ensure the website looks good on various devices and screen sizes.
- Interactive Elements: Implement interactive elements such as a navigation menu, buttons that change color when hovered over, or a light/dark mode toggle.
Hints to Get Started:
- HTML: Start by structuring your website with semantic HTML5 elements like
<header>
,<section>
,<footer>
, etc. - CSS: Use CSS for styling. Experiment with different layouts (like Flexbox or Grid), and add animations or transitions for a smoother user experience.
- JavaScript: Use JavaScript for interactive elements. For instance, a script to toggle between light and dark mode, or to validate form inputs.
- Version Control: Consider using Git for version control and GitHub for hosting your code repository.
- Testing and Debugging: Regularly test your website in different browsers and inspect elements to tweak the layout or debug.
- Learning Resources: Utilize resources like MDN Web Docs, W3Schools, or freeCodeCamp for reference or when you're stuck.
Remember, the key is to start simple and gradually add more features as you become more comfortable. This project will not only consolidate your learning but also serve as a showcase of your skills. Happy coding! 🚀💻
Potential Follow Ups
- Can you write out my first 10 tasks for this project?
- Can you guide me through this step by step?
Prompt #6: "Quiz me on XYZ subject"
Interactive quizzes with ChatGPT are excellent for beginners. Since ChatGPT basically knows everything, it can become super interactive!
Template
I just finished learning [XYZ concept]. Can you build me a comprehensive quiz that tests my knowledge of this and walk me through the quiz step by step?
Example
GPT Prompt
Quiz Prompt
Prompt
I just finished learning Java. Can you build me a comprehensive quiz that tests my knowledge of the language and walk me through the quiz step by step?
Prompt Response
Certainly! I can create a comprehensive Java quiz for you. This quiz will cover various aspects of Java programming, including syntax, core concepts, object-oriented principles, standard libraries, and practical application. We'll go through it step by step.
Java Quiz
Question 1: Basic Syntax
- What is the purpose of the
main
method in a Java program?
Question 2: Data Types
- What is the difference between
int
anddouble
data types in Java?
Question 3: Control Structures
- Explain how a
for
loop works in Java with an example.
Question 4: Object-Oriented Programming
- What is the difference between a class and an object in Java?
Question 5: Inheritance
- How do you achieve inheritance in Java?
Question 6: Polymorphism
- Give an example of method overloading and method overriding in Java.
Question 7: Exception Handling
- What is a
try-catch
block, and why is it used?
Question 8: Collections Framework
- What is the difference between a
List
and aSet
in Java?
Question 9: Streams and Lambda Expressions
- Explain what a stream is in Java and give a simple example of its usage.
Question 10: Concurrency
- What is the difference between
Runnable
andThread
in Java?
Feel free to answer these questions one by one, and I will provide feedback and explanations for each. Let's start with Question 1: What is the purpose of the main
method in a Java program?
Prompt #7: "What are some tools I can use to help with..."
While ChatGPT isn't always up-to-date on the latest information, for well-established toolsets, it can be a huge help in finding the right tool for the job.
Template
I'm building [project title]. It will have the following features:
- [Feature 1]
- [Feature 2]
- [Feature 3]
What tools or technologies would be well-suited for this type of project? I am most comfortable with the [your favorite language] programming language.
Example
GPT Prompt
Tools Prompt
Prompt
I'm building a restaurant directory in my city. It will have the following features:
- Interactive map
- Search bar
- Reservation booking
What tools or technologies would be well-suited for this type of project? I am most comfortable with the JavaScript programming language.
Prompt Response
Building a restaurant directory with features like an interactive map, search bar, and reservation booking system, especially when using JavaScript, involves a mix of frontend and backend technologies. Here's a breakdown of the tools and technologies that could be well-suited for each aspect of your project:
Interactive Map
- Google Maps API: This is a popular choice for integrating interactive maps. It allows you to display custom maps and place markers, and it's easy to use with JavaScript.
- Leaflet: An open-source alternative to Google Maps. It's lightweight and can be used with various map providers.
- Mapbox: Offers more customization options than Google Maps and is also well-integrated with JavaScript.
Search Bar
- Elasticsearch: A powerful search engine that can handle complex search requirements, including full-text search, which is great for searching through restaurant names, cuisines, etc.
- Algolia: A hosted search service that offers a fast and responsive search experience. It's easy to integrate with JavaScript applications.
- Firebase Firestore: If you're already using Firebase for your backend, Firestore's query capabilities can be utilized to implement efficient search functionality.
Reservation Booking
- Node.js with Express: For the backend, Node.js is a natural choice given your comfort with JavaScript. Express.js can help you build the REST API for handling reservations.
- MongoDB: A popular NoSQL database that pairs well with Node.js for storing reservation data.
- Firebase Realtime Database: Another good option for real-time data handling, which can be useful for updating reservation slots instantly.
Frontend Frameworks
- React: A popular JavaScript library for building user interfaces. It's great for building complex, interactive web apps like your directory.
- Vue.js: Another lightweight and easy-to-learn framework that could be used to build your front end.
Backend as a Service (BaaS)
- Firebase: Offers various services like authentication, database management, and hosting. It's a good choice if you want to reduce backend development time.
- AWS Amplify: Provides a broad range of services including authentication, data storage, and API development, which can be beneficial for a project like yours.
Additional Tools
- Git and GitHub for version control.
- Webpack or Parcel for bundling your JavaScript code.
- SASS or LESS for advanced CSS management.
- Bootstrap or Tailwind CSS for responsive design and pre-built components.
Deployment
- Netlify or Vercel: For frontend deployment, both are excellent choices offering seamless integration with Git.
- Heroku or AWS: For backend deployment, depending on your needs.
Testing Tools
- Jest for unit testing.
- Cypress or Selenium for end-to-end testing.
Selecting the right mix of these technologies will depend on your specific requirements, scalability needs, and personal preferences. Since you are comfortable with JavaScript, many of these tools should fit well within your skill set.
The pitfalls of this prompt
Be careful with this one. The recommendations ChatGPT gives will never be perfect for your situation.
Use them as a starting point to discover tools that you may not have known about. Then, go research those tools in depth!
Choosing the correct tools for your project is a super important step and should not be rushed through.
ChatGPT Prompts for Writing Code
Believe it or not, ChatGPT can write some pretty outstanding code if prompted correctly. Here are the prompts I use to get the most out of it.
Prompt #1: "Help me build my data model"
One area that I've found ChatGPT to excel at is data modeling. This is a super important first step to building any project and I use ChatGPT extensively during this process to come up with better data relationships and find things that I might have missed on my own.
All that said, if you don't have foundational knowledge in data modeling, it will be a little bit harder to work with this prompt.
Template
Can you help me build a data model? Here are the entities that I have so far:
- Entity 1
- Entity 2
I am building an app that [describe what your app will do]
Show me what this data model should look like and how I can improve it.
Example
GPT Prompt
Data Modeling Prompt
Prompt
Can you help me build a data model? Here are the entities that I have so far:
- User
- Restaurant
- Location
- Reservation
I am building an app where users can search for restaurants near them and book reservations.
Show me what this data model should look like and how I can improve it.
Prompt Response
Building a data model for your app involves defining the entities and their relationships. Let's start with the entities you've listed and build a basic model around them. We will also consider additional attributes for each entity that might be useful for your application.
- User: Represents the customers using your app.
- Attributes: UserID, Name, Email, Phone Number, Password.
- Restaurant: Represents the restaurants users can book.
- Attributes: RestaurantID, Name, LocationID, Cuisine Type, Average Rating, Price Range.
- Location: Represents the physical location of restaurants.
- Attributes: LocationID, Address, City, State, Zip Code, Country, Geo-coordinates (Latitude, Longitude).
- Reservation: Represents the booking details.
- Attributes: ReservationID, UserID, RestaurantID, Reservation Date & Time, Number of People, Special Requests.
Now let's define the relationships:
- User to Reservation: One-to-Many (One user can have multiple reservations, but each reservation is associated with one user).
- Restaurant to Reservation: One-to-Many (One restaurant can have multiple reservations, but each reservation is for one restaurant).
- Restaurant to Location: One-to-One (Each restaurant is associated with one location).
To improve this model:
- Reviews: You might want to add a 'Review' entity where users can leave feedback about restaurants. This would have attributes like ReviewID, UserID, RestaurantID, Rating, Comment.
- Relationship: User to Review (One-to-Many), Restaurant to Review (One-to-Many).
- Favorites: Consider adding a feature where users can save their favorite restaurants. This would be a Many-to-Many relationship between Users and Restaurants.
- Restaurant Categories: To enhance restaurant search functionality, you might want to categorize restaurants (e.g., Italian, Chinese, Fast Food, etc.).
- User Preferences: Storing user preferences (cuisine, price range, etc.) can help in providing personalized recommendations.
- Payment Information: If handling payments through the app, a secure way to store payment information might be necessary.
The pitfalls of this prompt
ChatGPT can't build your entire data model for you. At some point, you'll have to step in and make some decisions.
Use this prompt as a starting point that gives you some ideas on where to take your project.
Prompt #2: "Build me a utility function that does XYZ"
This is one of my favorite prompts. I use this all the time to speed up my development workflow.
Template
Build me a [coding language] utility function that [describe what it does]. It should accept the following parameters as input: [list inputs]
Example
GPT Prompt
Utility Function Prompt
Prompt
Build me a TypeScript utility function that calculates a mortgage payment. This function should accept a loan amount, term, and interest rate as inputs.
Prompt Response
Sure, I can help you with that. To create a TypeScript utility function to calculate a mortgage payment, you'll need to use the formula for calculating the monthly payment of an amortizing loan. The formula is:
M = P * (r * (1 + r)^n) / ((1 + r)^n - 1)
Where:
M is the monthly payment
P is the principal loan amount
r is the monthly interest rate (annual interest rate divided by 12)
n is the number of payments (loan term in years multiplied by 12)
Here's how you can implement this in TypeScript:
function calculateMortgage(loanAmount: number, termInYears: number, annualInterestRate: number): number {
const monthlyInterestRate = annualInterestRate / 12 / 100;
const numberOfPayments = termInYears * 12;
const monthlyPayment =
loanAmount *
monthlyInterestRate *
Math.pow(1 + monthlyInterestRate, numberOfPayments) /
(Math.pow(1 + monthlyInterestRate, numberOfPayments) - 1);
return monthlyPayment;
}
// Example usage:
const loanAmount = 300000; // e.g., $300,000
const termInYears = 30; // e.g., 30 years
const annualInterestRate = 3.5; // e.g., 3.5%
const monthlyPayment = calculateMortgage(loanAmount, termInYears, annualInterestRate);
console.log(`Monthly Payment: $${monthlyPayment.toFixed(2)}`);
In this function:
loanAmount
is the total amount of the loan.termInYears
is the duration of the loan in years.annualInterestRate
is the annual interest rate (as a percentage).
The function calculates the monthly payment based on these inputs and returns it. The example usage shows how to call this function with specific values and print the result.
Remember that the actual mortgage payment could include other factors like property taxes, homeowner's insurance, and possibly private mortgage insurance (PMI), which are not accounted for in this basic calculation.
ChatGPT Prompts for Debugging and Code Review
Oftentimes, you'll have to write a bunch of code without the help of ChatGPT due to the complexity. But once you've completed it, ChatGPT can be an excellent "auditor" to show you how to either fix or improve it.
Prompt #1: "Fix my code"
This prompt is especially useful for beginners when you're learning the syntax of a new programming language.
Template
This code does not work. Can you fix it?
```
Put your code here
```
Example
GPT Prompt
Fix my code Prompt
Prompt
This code doesn't work. Can you fix it?
```
export function formatDuration(
seconds: number,
showHours = false
): DurationObject {
const duration = showHours
? Duration.fromObject({ seconds }).shiftTo("hours", "minutes", "seconds")
: Duration.fromObject({ seconds }).shiftTo("minutes", "seconds");
const standard = duration.toFormat("hh:mm:ss");
const parts = standard.split(":";
const standardFinal = parts[0] === "00" ? parts.slice(1).join(":") : standard;
return {
formatted: duration.toHuman( unitDisplay: "short" }),
formattedStandard: standardFinal,
hours: duration.hours,
minutes: duration.minutes,
seconds: duration.seconds,
};
}
```
Prompt Response
It looks like there are a few syntax errors in your code. Let's fix them:
- There's a missing closing parenthesis in the
parts
variable assignment. - The
toHuman()
method call has a syntax error in its options object. - Ensure that you're using a valid library or framework that defines
Duration
and its methods (fromObject
,shiftTo
,toFormat
,toHuman
, etc.). If this is from a specific library like Luxon, make sure to import it correctly.
Here's the corrected version of your code:
import { Duration } from 'luxon'; // Assuming you're using Luxon, ensure this import is correct for your library
export function formatDuration(seconds: number, showHours = false): DurationObject {
const duration = showHours
? Duration.fromObject({ seconds }).shiftTo("hours", "minutes", "seconds")
: Duration.fromObject({ seconds }).shiftTo("minutes", "seconds");
const standard = duration.toFormat("hh:mm:ss");
const parts = standard.split(":"); // Corrected the missing parenthesis
const standardFinal = parts[0] === "00" ? parts.slice(1).join(":") : standard;
return {
formatted: duration.toHuman({ unitDisplay: "short" }), // Corrected syntax for the options object
formattedStandard: standardFinal,
hours: duration.hours,
minutes: duration.minutes,
seconds: duration.seconds,
};
}
Please ensure that the Duration
and its methods are correctly referenced from the library you are using. The above corrections are made assuming Luxon's Duration
object. If you're using a different library, you'll need to adjust the import and method usage accordingly.
Prompt #2: "Can you improve my code?"
This prompt works well for beginner code and is hit or miss with more advanced code.
Template
Can you improve my code?
```
Add your code here
```
Example
GPT Prompt
Improve my code Prompt
Prompt
Can you improve my code?
```
var globalVar = "I am a global variable";
function doStuff() {
for (i = 0; i < 5; i++) {
console.log(globalVar);
}
}
doStuff();
```
Prompt Response
Certainly! Your JavaScript code snippet can be improved in several ways for better practices and readability. Here's an enhanced version of your code with explanations for the changes made:
// Use 'let' or 'const' for variable declaration to avoid implicit global scope
const globalVar = "I am a global variable";
function doStuff() {
// Declare 'i' with 'let' for block scope, avoiding accidental global variable creation
for (let i = 0; i < 5; i++) {
console.log(globalVar);
}
}
doStuff();
Improvements Made:
- Variable Declaration with
const
: TheglobalVar
is declared withconst
since its value doesn't change. This is a best practice to avoid accidental reassignment. If you plan to change its value, uselet
instead. - Block Scope Variable: Inside the
for
loop,i
is declared withlet
, which restricts its scope to the loop block. Previously,i
was implicitly declared as a global variable, which could lead to unexpected behavior in larger applications.
These changes make your code more robust and maintainable by adhering to modern JavaScript best practices.
Prompt #3: "What best practices should I use for XYZ?"
If you think about it, ChatGPT essentially knows all public information on the internet. In many cases, it can be a great "senior developer" to guide you through a coding problem using "best practices" (i.e. industry standard techniques).
It doesn't always get things right though. Use these answers to get you started, but always try to get a second opinion.
Template
I'm building [describe project] with [list technologies]. Can you give me some "best practices" that I should follow?
Example
GPT Prompt
Best Practices Prompt
Prompt
I'm building my own user authentication with Node.js and React. Can you give me some "best practices" to use here?
Prompt Response
Building a user authentication system with Node.js and React involves several best practices to ensure security, efficiency, and a good user experience. Here are some key points to consider:
- Use a Secure Authentication Protocol: Implement a standard, proven authentication protocol like OAuth2 or OpenID Connect. These protocols have been thoroughly tested and are widely used, reducing the risk of vulnerabilities in your custom implementation.
- Password Management:
- Hash Passwords: Always hash user passwords using a strong hashing algorithm like bcrypt. Never store plain-text passwords.
- Salt Passwords: Use a unique salt for each password to prevent rainbow table attacks.
- Password Strength: Implement rules for password complexity to ensure strong user passwords.
- Session Management:
- Use HTTPS: Always use HTTPS to protect data in transit.
- Secure Cookies: If using cookies for session management, set them as 'HttpOnly' and 'Secure'.
- Token Expiration: Implement token expiration and automatic logouts after periods of inactivity.
- Input Validation and Sanitization: Always validate and sanitize user input to prevent SQL injection, XSS attacks, and other common web security vulnerabilities.
- Error Handling:
- Avoid Detailed Error Messages: Don't reveal too much information in error messages. For instance, if a login fails, use a generic message like "Invalid username or password" rather than specifying which one is incorrect.
- Log Errors: Log errors server-side for monitoring and debugging purposes.
- User Feedback: Provide clear, user-friendly feedback for actions like registration, login, and password recovery.
- Two-Factor Authentication (2FA): Consider implementing 2FA to add an extra layer of security. This can be done via SMS, email, or authenticator apps.
- Cross-Origin Resource Sharing (CORS): If your API and client are served from different domains, ensure that you configure CORS properly in your Node.js application.
- Use JSON Web Tokens (JWT): For stateless authentication, use JWT. It's a good way to handle authentication in a scalable way, especially for single page applications (SPAs).
- Regular Updates and Security Audits: Regularly update your dependencies to include security patches. Conduct periodic security audits to identify and fix vulnerabilities.
- Rate Limiting and Brute Force Protection: Implement rate limiting on your login endpoints to prevent brute force attacks.
- User Data Privacy: Be transparent about how you use and store user data and comply with data protection regulations like GDPR.
By following these best practices, you'll create a more secure and efficient authentication system for your Node.js and React application. Remember, security is an ongoing process and it's important to stay updated with the latest trends and threats in web security.
Prompt #4: "What are the trade-offs?"
I love this prompt. As engineers, we are constantly weighing the pros and cons of a given problem-solving approach. When building things, there is often no "correct" answer—just trade-offs.
ChatGPT is great at listing these out for you so you can make better decisions.
Template
I'm building [XYZ project]. This app will [describe what it does]
I'm currently using the following approach: [describe how you're solving a problem in the app]
What are the tradeoffs to this approach vs. other options like [list alternatives you have considered]
Example
GPT Prompt
Trade-offs Prompt
Prompt
I'm building an image compression service. The user will upload an image, select a transformation, and then wait until the transformation is complete.
I send each image request to a background job and then use long-polling to detect when it is finished and alert the user.
What are the tradeoffs to this approach vs. other options like websockets or server sent events?
Prompt Response
Your image compression service, which utilizes long-polling for updating the status of image transformation jobs, presents several trade-offs when compared to alternatives like WebSockets or Server-Sent Events (SSE). Let's explore these trade-offs:
Long-Polling
Pros:
- Compatibility: Long-polling is widely supported across various browsers and doesn't require modern browser capabilities.
- Simplicity: It's relatively simple to implement on both the client and server sides, especially if the existing infrastructure doesn't support persistent connections.
- HTTP-based: It fits well into the standard request-response model of HTTP, making it easy to integrate with existing web technologies.
Cons:
- Inefficiency: Long-polling can be less efficient than WebSockets or SSE, as it involves repeatedly closing and reopening HTTP connections. This can lead to increased latency and server load.
- Scalability Issues: It may not scale well under high loads or in real-time applications, as each poll is a new HTTP request, increasing the server's load.
- Limited by HTTP Constraints: Being tied to HTTP, it inherits all limitations of the protocol, like header overheads and no native support for binary data.
WebSockets
Pros:
- Real-Time Communication: Offers true bidirectional, full-duplex communication, ideal for real-time applications.
- Efficiency: After the initial handshake, data can be sent with minimal overhead, reducing latency.
- Binary Data Support: Natively supports both text and binary data, making it suitable for a variety of data types.
Cons:
- Complexity: More complex to implement and requires server infrastructure that can maintain persistent connections.
- Compatibility Issues: Older browsers and certain network proxies/firewalls might not support WebSockets.
- Resource Utilization: Keeping a large number of WebSocket connections open can consume more server resources.
Server-Sent Events (SSE)
Pros:
- Simplicity and HTTP-based: Easier to implement than WebSockets and integrates easily with the existing web stack.
- Efficient for Unidirectional Data Flow: Ideal for scenarios where the server needs to push data to the client.
- Lower Resource Usage: Generally, uses fewer resources than WebSockets for maintaining open connections.
Cons:
- Unidirectional: Only supports server-to-client communication, not bidirectional.
- Limited Browser Support: Not as widely supported in browsers as WebSockets, especially in older versions.
- Limited by HTTP: Like long-polling, it's bound by the limitations of HTTP, including potential inefficiencies in headers and text-based data transfer.
Conclusion
The choice between long-polling, WebSockets, and SSE depends on your specific application needs:
- If you need real-time bidirectional communication and can handle the complexity, WebSockets are preferable.
- For simpler, unidirectional updates where real-time isn't crucial, SSE is a good choice.
- Long-polling is suitable for environments where compatibility and simplicity are more important than efficiency and real-time communication.
Chat GPT Prompts for Building User Interfaces
When it comes to building user interfaces, there are tons of tools popping up all over the place. ChatGPT is probably not the best tool for the job, but can be super helpful when building basic UI components and interactions.
Prompt #1: "Using X, Y, Z, build me a component"
I generally reserve this prompt for simple components to get me started. After ChatGPT generates the UI component, I'll edit it manually. This saves me a lot of time!
Template
Using [list technologies], build me a [feature you need built]
Example
GPT Prompt
Build me XYZ Prompt
Prompt
Using TailwindCSS, React, TypeScript, and HeadlessUI, build me a light mode / dark mode toggle I can put in my navbar.
Prompt Response
Creating a light mode/dark mode toggle using TailwindCSS, React, TypeScript, and HeadlessUI involves several steps. Here's a basic implementation that you can customize and integrate into your navbar:
- Setup TailwindCSS: Make sure TailwindCSS is properly set up in your project. If it's not already set up, you can follow the installation guide on the TailwindCSS website.
- Create a Toggle Component: We will create a React component for the toggle.
- Use HeadlessUI: We'll utilize HeadlessUI for accessible UI components, although for a simple toggle, its direct utility might be limited.
- Handle State and Theming: We'll manage the light/dark mode state and implement the necessary logic for switching themes.
Here's a basic example of how you might write this component:
// Import React and necessary hooks
import React, { useState, useEffect } from 'react';
// LightDarkToggle.tsx
const LightDarkToggle: React.FC = () => {
// State to track whether dark mode is enabled
const [darkMode, setDarkMode] = useState(false);
// Effect to apply the theme on initial render
useEffect(() => {
if (window.localStorage.getItem('theme') === 'dark' || (!('theme' in window.localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
setDarkMode(true);
} else {
setDarkMode(false);
}
}, []);
// Function to toggle dark mode
const toggleDarkMode = () => {
setDarkMode(!darkMode);
if (darkMode) {
document.documentElement.classList.add('dark');
window.localStorage.setItem('theme', 'dark');
} else {
document.documentElement.classList.remove('dark');
window.localStorage.setItem('theme', 'light');
}
};
return (
<button onClick={toggleDarkMode} className="p-2 rounded-md focus:outline-none focus:ring">
{darkMode ? 'Light Mode' : 'Dark Mode'}
</button>
);
};
export default LightDarkToggle;
- Integrate into Navbar: Finally, import and use this component in your navbar component.
- TailwindCSS Configuration: Ensure your
tailwind.config.js
is set up to handle dark mode, usually with thedarkMode: 'class'
option. This allows Tailwind to apply dark mode styles when thedark
class is present on thehtml
orbody
element. - Styling: Style the toggle button using TailwindCSS classes as per your design requirements.
Remember, this is a basic implementation. You might need to adjust it based on your specific project setup and requirements.
Prompt #2: "Transform this code into..."
I don't use this too often, but every once in a while, I'll stumble on a code snippet that is close to what I need, but needs to be entirely rewritten in the tech stack I'm using.
Template
Can you transform this [language] code to [language]?
Example
GPT Prompt
Code Transformation Prompt
Prompt
Can you transform this PHP function to TypeScript?
```
function calculateReadingTime($text) {
$wordCount = str_word_count(strip_tags($text));
$wordsPerMinute = 200; // Average reading speed of an adult
$readingTime = ceil($wordCount / $wordsPerMinute);
return $readingTime;
}
```
Prompt Response
Certainly! The PHP function you provided can be translated to TypeScript as follows:
function calculateReadingTime(text: string): number {
const wordCount = text.replace(/<[^>]*>/g, '').split(/\s+/).length;
const wordsPerMinute = 200; // Average reading speed of an adult
const readingTime = Math.ceil(wordCount / wordsPerMinute);
return readingTime;
}
This TypeScript function does the following:
- Removes HTML tags from the input string using a regular expression.
- Splits the string into words based on whitespace.
- Calculates the word count.
- Calculates the reading time by dividing the word count by the average words per minute (set to 200, as in your PHP function).
- Returns the reading time, rounded up to the nearest whole number using
Math.ceil
.
Chat GPT Prompts for Writing Scripts and One-Liners
Last, but certainly not least, let's write some scripts with ChatGPT. This may be one of the biggest time-saving scripts in this entire post. I use these all the time.
Prompt #1: "Write a bash script"
ChatGPT is scary good as writing bash scripts. Once you learn the basics of Bash, it can be an excellent sidekick.
Template
Write me a bash script that [explain what it does]
Example
GPT Prompt
Bash Script Prompt
Prompt
Write me a bash script that will find all files in my ~/Documents/zach directory that end in jpg, JPG, png, or PNG and copy them to the ~/Documents/zach/media folder.
Prompt Response
Certainly! Here's a Bash script that will do exactly what you described. This script will find all files in the ~/Documents/zach
directory that end in jpg
, JPG
, png
, or PNG
and copy them to the ~/Documents/zach/media
folder.
#!/bin/bash
# Source directory
source_dir="$HOME/Documents/zach"
# Destination directory
dest_dir="$HOME/Documents/zach/media"
# Create destination directory if it doesn't exist
mkdir -p "$dest_dir"
# Find and copy the files
find "$source_dir" -type f \( -iname "*.jpg" -o -iname "*.png" \) -exec cp {} "$dest_dir" \;
echo "Files copied to $dest_dir"
To use this script:
- Copy the script into a file, for example,
copy_images.sh
. - Make the script executable with the command:
chmod +x copy_images.sh
. - Run the script:
./copy_images.sh
.
This script will:
- Create the destination directory if it doesn't exist.
- Use the
find
command to search for files ending with.jpg
,.JPG
,.png
, or.PNG
in the specified source directory. - Copy these files to the destination directory.
- Print a message once the copying is complete.
Prompt #2: "Build me a script in [language] that..."
And finally, a variation of the bash script above.
Template
Write a script in [language] that performs the following steps:
1. Step 1
2. Step 2
3. Step 3
Example
GPT Prompt
Script Writer Prompt
Prompt
Write a script in JavaScript that performs the following steps:
1. Goes to a YouTube channel
2. Finds the top 10 videos by view count
3. Saves the title, a URL to the thumbnail, and view count in a file called `youtube.txt`
Prompt Response
To create a JavaScript script that accomplishes these tasks, you would need to interact with the YouTube Data API, as scraping YouTube directly through a script violates their terms of service. The YouTube Data API provides a way to programmatically access YouTube data including video titles, thumbnails, and view counts.
Here's an outline of how you can write such a script:
- Set Up YouTube Data API: You need to set up the YouTube Data API in the Google Developers Console. Create a project and enable the YouTube Data API v3 for that project. Then, create credentials (an API key) for accessing the API.
- Write the Script: You can use Node.js with the
googleapis
library to interact with the YouTube API. The script will make a request to the API to fetch the top 10 videos by view count for a given channel. - Save Data to a File: The script will then save the required details (title, thumbnail URL, view count) to a file called
youtube.txt
.
Here's an example script that demonstrates these steps:
const { google } = require('googleapis');
const fs = require('fs');
const path = require('path');
const youtube = google.youtube({
version: 'v3',
auth: 'YOUR_API_KEY' // Replace with your API key
});
async function getTopVideos(channelId) {
const response = await youtube.search.list({
part: 'snippet',
channelId: channelId,
order: 'viewCount',
maxResults: 10,
type: 'video'
});
const videoDetails = response.data.items.map(item => {
return {
title: item.snippet.title,
thumbnailUrl: item.snippet.thumbnails.high.url,
videoId: item.id.videoId
};
});
return videoDetails;
}
async function saveToFile(channelId, filename) {
try {
const videos = await getTopVideos(channelId);
const fileContent = videos.map(video =>
`Title: ${video.title}, Thumbnail URL: ${video.thumbnailUrl}, Video ID: ${video.videoId}`
).join('\n');
fs.writeFileSync(path.join(__dirname, filename), fileContent);
console.log(`Data saved to ${filename}`);
} catch (error) {
console.error('Error:', error);
}
}
// Replace with the desired YouTube channel ID and filename
saveToFile('CHANNEL_ID', 'youtube.txt');
Important Notes:
- Replace
'YOUR_API_KEY'
with your actual API key. - Replace
'CHANNEL_ID'
with the ID of the YouTube channel you're interested in. - This script uses Node.js and requires the
googleapis
package, which you can install usingnpm install googleapis
. - The script saves data in a simple text format. You might need to adjust the formatting based on your needs.
- Ensure that you have proper authorization and are complying with YouTube's terms of service and policies when using their API.
Concluding Thoughts: Too Much Reliance on AI?
My mission here at Full Stack Foundations is to help developers build a rock-solid foundation of knowledge and skills so they can level up in their careers.
As you incorporate AI into your workflows, try and strike a balance between being effective and learning concepts.
When I first learned to code, I deliberately would type out code examples line by line so that I could better understand what the code is doing. In the age of LLMs like ChatGPT, it can be tempting to employ the "copy/paste" strategy and never really sit down to learn what you're doing.
For small projects, this strategy works fine. But when you start working in the field and get thrown into a complex codebase, relying on ChatGPT won't cut it.
So think of ChatGPT as your "coding assistant", not your crutch. ChatGPT is an excellent way to learn, but no substitute for putting in the work and time it takes to become a well-rounded software engineer.