DEV Community

Codelifter.com
Codelifter.com

Posted on

How Developers Can Use Artificial Intelligence to Write Code, Improve Their Workflow, Learn JavaScript and Build Maintainable Software

#ai

Introduction

Software development is undergoing significant changes due to the growing role of artificial intelligence (AI). Developers no longer rely solely on manual searches of documentation, nor do they write every single line of code completely from scratch. They can now utilize AI coding assistants to develop entire sections of code, explain complex programming concepts, offer suggestions to improve their code and assist in troubleshooting common issues related to development.
However, to obtain useful responses from an AI coding assistant, developers require more than just a brief set of directions. To begin with, developers must know how to construct effective prompts. Then developers must review the code generated by the AI to determine whether it meets their needs. Finally, developers must also check for potential security concerns and thoroughly test their implementation before placing it into a live application.
As mentioned earlier, JavaScript is a great place for developers to start exploring these opportunities since it is used for developing interactive web pages, browser-based applications, server-side development, and modern web user interfaces.

1. Learning About AI Assisting Development

AI assisted development means utilizing artificial intelligence to aid in various aspects of the software development process. Depending upon the specific goals and needs of a particular application, developers may use AI tools to:
Develop JavaScript code, including functions and other code segments.
Provide explanations of unfamiliar programming terms and concepts.
Offer solutions to common programming problems.
Help refactor repetitive code segments.
Develop test cases.
Produce documentation.
Explore alternate implementations.
Analyze existing source code bases.
To illustrate this concept let us assume that you needed to implement a function to compute the total cost of items within a shopping cart.
Rather than immediately writing out all of the code necessary to accomplish this task, you could ask an AI assistant to generate some sample JavaScript code that accomplishes the same thing along with providing an explanation of how the provided implementation works.
Here is a very simple example:
function calculateTotal(products) {
return products.reduce((total, product) => {
return total + product.price * product.quantity;
}, 0);
}

const cart = [
{ name: "keyboard", price: 50, quantity: 1 },
{ name: "mouse", price: 25, quantity: 2 }
];

console.log(calculateTotal(cart)); // 100
This example utilizes the reduce() method available in JavaScript to compute the sum of the costs of all items contained within a shopping cart.
Even though the above example is somewhat trivial it illustrates how an AI assistant can allow developers to rapidly find viable solutions to development challenges.
Any generated code must ultimately be reviewed for input validation, values that are not anticipated and project-specific requirements.

2. Creating Good Coding Prompts for AI Assistants

The quality of the code produced by an AI assistant is highly dependent on the quality of the instructions supplied.
Poorly written prompts will often produce working yet incomplete code.
Let us take a look at the following prompt:
"Write a JavaScript form."
There are no details regarding any required fields, how validation should occur, what actions should be taken once the form has been submitted etc...
Below is a rewritten version of the original prompt that includes much more detail:
"Write a JavaScript form validation function that determines whether the name and email fields were filled in properly; validates the email address entered; generates accessible error messages; prevents submission until there are valid entries in both fields. Do this using vanilla JavaScript without the assistance of any third party libraries."
This rewritten prompt provides a lot more useful context.
Developers should note that whenever possible a good coding prompt should include:
Objective: Define exactly what you wish to create.
Technology: Identify specifically JavaScript, TypeScript, React, Node.js or another applicable development environment.
Functional requirements: Outline how features should behave.
Technical constraints: Identify constraints on libraries, browser compatibility, performance, security etc...
Expected output: Ask for a complete function or component or even an explanation or test suite.
Additionally, developers may choose to request that an AI assistant explain their generated implementation line-by-line. This is especially useful for educating yourself on unfamiliar API calls or techniques.

3. A Practical JavaScript Example: Validating Forms

Validating forms is one of the most common requirements in web development.
Below is an example illustrating how to perform simple validation of form inputs using JavaScript.
function validateForm(name, email) {
var errors = [];

if (!name.trim()) {
errors.push("please fill in name");
}

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
if (!emailRegex.test(email)) {
errors.push('please enter a valid e-mail.');
}

return {
valid: errors.length == 0,
errors
};
};

var result = validateForm(
'alex',
'alex@example.com'
);

console.log(result);
This example performs two checks on the submitted form data:
First, it confirms that the name input field was populated with a non-whitespace value. Second, it verifies whether the email field was populated with a standard formatted email address.
This function returns an object that defines whether the input data is valid and an array of error messages describing why the data is invalid.
Given its structure this implementation is easily reused as it separates validation logic from user interface presentation logic.
That said, client-side validation alone is insufficient and applications must also validate untrusted data on the server side.

4. Utilizing AI to Diagnose Issues with Your JavaScript Code

Diagnosing is another area where AI coding assistants can prove beneficial.
If a developer experiences difficulties with a particular piece of code he/she can submit the relevant portion(s) of the problematic code and the corresponding error message along with a description of how the code should behave to an AI assistant.
To get better results please provide:
The full error message.
Relevant portion(s) of code segment.
Environment where problem occurs.
Expected output.
Actual output.
For instance, here is some sample code that will produce an error when run:
const users = undefined;

console.log(users.map(user => user.name));
The code fails because map() cannot be applied to undefined.
An AI assistant can describe why this occurred and suggest a safer way to implement this:
const users = [];
const names = users.map(user => user.name);
console.log(names);
Or, if the value may actually be missing in certain situations, developers may want to employ a fallback strategy:
const users = undefined;
const names = (users ?? []).map(
user => user.name
);

console.log(names);
The main point here is that developers should understand why something failed versus simply fixing whatever failed first.

5. Evaluating Generated Code for Quality

Regardless of how well generated code appears to work prior to being included in a project, it should always be evaluated carefully by a developer prior to inclusion in production code.
While a generated function may appear to operate correctly for simple test cases, it may fail under differing circumstances.
Thus, code evaluation should examine numerous aspects of code quality.
Readability: Were variable names and function names meaningful?
Maintainability: Was another developer able to understand and modify the implementation?
Performance: Did the code handle larger datasets effectively?
Error handling: What happens when inputs are missing or incorrect?
Browser compatibility: Does the implementation operate as intended within all browsers?
Security: Is there any potential for vulnerabilities that would expose the application?
Testing: Were normal cases and edge cases tested?
For example, a generated function that manipulates user submitted information should not automatically be trusted. Users must always be checked for validity alongside appropriate escaping of data for safe usage in the application.
AI can suggest improvements but ultimately the responsibility rests with the developer to evaluate the finalized implementation prior to release.

6. Test Your Implemented JavaScript Code Prior to Release

Testing helps confirm that your code behaves correctly under various conditions.
Example - assume we had developed a simple function to calculate discounts on products based upon price:
function calculateDiscount(price, percentage) {
return price - (price * percentage / 100);
}

console.log(calculateDiscount(100, 20)); // prints 80
The function operates as expected for our test case. However what if the price was negative or the discount percentage was greater than 100?
We may want to implement a more defensive strategy:
function calculateDiscount(price, percentage) {
if (
!Number.isFinite(price) ||
!Number.isFinite(percentage)
) {
throw new TypeError("Inputs must be finite numbers.");
}

if (price < 0 || percentage < 0 || percentage > 100) {
throw new RangeError("invalid price or discount.");
}

return price * (1 - (percentage / 100));
}
Now our function handles invalid input much more explicitly.
Developers can also utilize automated testing frameworks to verify that their implemented code behaves as expected across multiple scenarios.
AI assistants can help developers generate test cases but those test cases should still be thoroughly evaluated by developers to ensure that they cover reasonable requirements.
Visit us at Codelifter.com

Top comments (0)