Prompt To Build

Create real apps with AI

Chapter 5: From Zero to Function - Building Blocks of Code

The Smallest Units: Functions and Variables

In Starting Forth, you would have learned about "words" – the fundamental building blocks of the Forth language. In JavaScript, our primary building blocks are variables and functions. Variables are like containers that hold information, and functions are reusable blocks of code that perform specific tasks. Understanding how to prompt AI to generate these effectively is your next crucial step.

This chapter will guide you through prompting AI to create variables, define functions, and understand their basic interactions. We will start simple and gradually build up to more complex function structures.

Variables: Storing Information

Variables are essential for storing data that your program needs to work with. In JavaScript, you declare variables using let, const, or (less commonly now) var.

  • let: Used for variables whose values might change.
  • const: Used for variables whose values will not change (constants).
  • var: An older keyword, generally avoided in modern JavaScript due to its scope rules.

Example 1: Declaring Variables

Goal:
Declare a variable to store a user's name and another for their age.
Prompt:
Declare two JavaScript variables: 
one named userName to store a string value "Alice",
and another named userAge to store a number value 30.
Use modern JavaScript syntax.
AI-Generated Code (Expected):
const userName = "Alice";
let userAge = 30;
  • Analysis: The AI correctly uses const for a value that is unlikely to change (name) and let for one that might (age), demonstrating an understanding of modern JavaScript conventions.

Example 2: Performing Operations with Variables

Goal:
Calculate the area of a rectangle using variables for length and width.
Prompt:
Write JavaScript code to declare two variables, 
length set to 10 and
width set to 5.
Then, calculate their product and store it in a new variable called area.
Finally, print the area to the console.
AI-Generated Code (Expected):
const length = 10;
const width = 5;
const area = length * width;
console.log("The area is: " + area);
// Expected output: The area is: 50
  • Analysis: The AI correctly performs arithmetic operations and demonstrates how to output results, a fundamental programming concept.

Functions: Reusable Blocks of Code

Functions are the workhorses of JavaScript. They allow you to encapsulate a specific task into a reusable block, making your code organized, efficient, and easier to debug. Functions can take inputs (arguments) and produce outputs (return values).

Example 3: A Simple Function

Goal:
Create a function that greets a user by name.
Prompt:
Write a JavaScript function named greetUser that takes one argument, name, 
and returns a string like "Hello, [name]!".
AI-Generated Code (Expected):
function greetUser(name) {
  return `Hello, ${name}!`; // Using template literals for easy string formatting
}

// Example usage:
// console.log(greetUser("Bob")); // Expected output: Hello, Bob!
  • Analysis: The AI correctly defines a function, uses a parameter, and returns a formatted string. The use of template literals (`) is a modern JavaScript feature that makes string concatenation cleaner.

Example 4: Function with Multiple Arguments

Goal:
A function to calculate the average of three numbers.
Prompt:
Create a JavaScript function called calculateAverage that accepts 
three numbers as arguments (num1, num2, num3) and returns their average.
AI-Generated Code (Expected):
function calculateAverage(num1, num2, num3) {
  return (num1 + num2 + num3) / 3;
}

// Example usage:
// console.log(calculateAverage(10, 20, 30)); // Expected output: 20
  • Analysis: This demonstrates how functions can handle multiple inputs and perform calculations based on them.

Example 5: Functions Calling Other Functions

Just as Forth words can be combined to create new words, JavaScript functions can call other functions. This is a powerful way to build complex logic from simpler, reusable parts.

Goal:
Calculate the total cost including tax, using separate functions for subtotal and tax calculation.
Prompt:
First, write a JavaScript function calculateSubtotal that returns the sum of an array of prices.

Second, write a JavaScript function calculateTax that returns the tax amount on the subtotal: 
use the given tax rate (e.g., 0.05 for 5%).

Finally, write a function calculateTotalCost that takes an array of prices and a tax rate. 

This function should use calculateSubtotal and calculateTax to compute and return the final total cost.
AI-Generated Code (Expected):
function calculateSubtotal(prices) {
  let subtotal = 0; 
  for (let i = 0; i < prices.length; i++) { 
    subtotal += prices[i]; 
  } 
  return subtotal;
}

function calculateTax(subtotal, taxRate) { 
  return subtotal * taxRate; 
} 

function calculateTotalCost(prices, taxRate) {
  const subtotal = calculateSubtotal(prices);
  const taxAmount = calculateTax(subtotal, taxRate);
  return subtotal + taxAmount;
} 

// Example usage:
// const itemPrices = [100, 50, 25];
// const salesTaxRate = 0.08; // 8%
// console.log(calculateTotalCost(itemPrices, salesTaxRate));
// Expected output: (100+50+25) + (100+50+25)*0.08 = 175 + 14 = 189
  • Analysis: This example beautifully illustrates modularity. The AI correctly breaks down the problem into smaller, interconnected functions, demonstrating a fundamental principle of good software design.

Conclusion: Your Growing Vocabulary

You've now mastered the basic "words" of JavaScript: variables and functions. You can prompt AI to create them, manipulate them, and combine them to perform more complex tasks. This foundational knowledge is crucial for building any JavaScript application. In the next chapter, we will explore how to work with collections of data, such as lists and dictionaries.

---

References: From Zero to Function