INF 270: WordPress — Week 12: Javascript

Announcements

Your second Final Project Check-In is due this week on Sunday.

There is one additional Lab in 2 weeks, and after that your final project is due on May 3rd.

Final Project Details

JavaScript Variables

Open up CodePen to follow along.

A variable is a named container for storing a value. In modern JavaScript, you declare variables with let or const.

  • let — use this when the value might change later (a score, a counter, a form input)
  • const — use this when the value should stay fixed (a site name, a tax rate, a configuration value)

You will also encounter var in older code. Avoid writing it yourself — it has confusing behavior around scope that let and const were designed to fix.

// let: a variable whose value can change
let score = 10;
score = 20; // allowed

// const: a variable that cannot be reassigned
const siteName = "Blue Ridge Pottery";
// siteName = "Other"; // this would throw an error

// var: the old way — avoid it in modern JS
var oldStyle = "don't use this";

console.log(score);
console.log(siteName);

2. Data Types

Every value in JavaScript has a type. You don't have to declare the type yourself — JavaScript figures it out from what you assign. You can check a value's type with the typeof operator.

// String
let name = "Alice";
let greeting = `Hello, ${name}!`; // template literal

// Number (integers and decimals are the same type)
let price = 19.99;
let quantity = 3;

// Boolean
let isLoggedIn = true;
let hasDiscount = false;

// Null (intentionally empty)
let couponCode = null;

// Undefined (declared but not yet assigned)
let shippingAddress;

// Array (ordered list of values)
let colors = ["red", "green", "blue"];

// Object (key-value pairs)
let product = {
  name: "Speckled Mug",
  price: 28,
  inStock: true,
};

console.log(greeting);
console.log(typeof price);       // "number"
console.log(typeof isLoggedIn);  // "boolean"
console.log(colors[0]);          // "red" (arrays start at index 0)
console.log(product.name);       // "Speckled Mug"
Strings and template literals. A template literal uses backtick characters (`) instead of quotes. Inside it, you can embed any variable or expression using ${'$'}{variableName}. This is almost always cleaner than joining strings with +.

3. Operators

Operators let you perform calculations, compare values, and combine conditions.

// Arithmetic
let a = 10;
let b = 3;
console.log(a + b);  // 13
console.log(a - b);  // 7
console.log(a * b);  // 30
console.log(a / b);  // 3.333...
console.log(a % b);  // 1 (remainder/modulo)

// Increment / decrement
let count = 0;
count++;          // count is now 1
count--;          // count is now 0

// String concatenation
let firstName = "Ada";
let lastName = "Lovelace";
console.log(firstName + " " + lastName);

// Template literals (cleaner way)
console.log(`${firstName} ${lastName}`);

// Comparison operators — always returns true or false
console.log(5 === 5);   // true  (strict equality — preferred)
console.log(5 !== 3);   // true  (strict not-equal)
console.log(10 > 3);    // true
console.log(10 <= 10);  // true

// Logical operators
console.log(true && false);  // false (AND — both must be true)
console.log(true || false);  // true  (OR  — at least one must be true)
console.log(!true);          // false (NOT — flips the value)
Use === not ==. JavaScript has two equality operators. === (strict equality) checks that the value and the type match. == does type coercion, which produces surprising results (0 == false is true). Always use ===.

4. Conditional Logic

Conditionals let your code make decisions. The most common is if / else if / else. For checking one variable against many exact values, switch is often cleaner.

let temperature = 72;

if (temperature > 85) {
  console.log("It's hot outside.");
} else if (temperature > 60) {
  console.log("Nice weather!");
} else {
  console.log("Bring a jacket.");
}

// A practical example: showing a price with or without discount
let price = 50;
let memberDiscount = true;

let finalPrice = memberDiscount ? price * 0.9 : price;
// The line above is called a "ternary" — a compact if/else
// condition ? valueIfTrue : valueIfFalse

console.log("Final price: $" + finalPrice);

// switch is useful when one variable matches several exact values
let day = "Monday";

switch (day) {
  case "Saturday":
  case "Sunday":
    console.log("Weekend — store closed.");
    break;
  case "Monday":
    console.log("Start of the week.");
    break;
  default:
    console.log("Regular business day.");
}

5. Loops

Loops repeat a block of code. The right loop depends on what you are iterating over.

  • for — when you need a counter (run this exactly 5 times)
  • while — when you repeat until a condition becomes false
  • forEach / for...of — when you are working through an array and don't need a counter
// for loop: when you know how many times to repeat
for (let i = 1; i <= 5; i++) {
  console.log("Step " + i);
}

// while loop: repeats as long as a condition is true
let stock = 3;
while (stock > 0) {
  console.log("Items remaining: " + stock);
  stock--;
}

// forEach: the cleanest way to loop over an array
let products = ["Mug", "Bowl", "Vase"];

products.forEach(function(product) {
  console.log("Product: " + product);
});

// Arrow function shorthand (same result, less typing)
products.forEach((product) => {
  console.log("Product: " + product);
});

// for...of: another readable way to loop over an array
for (let product of products) {
  console.log(product);
}

6. Functions

A function is a reusable block of code. You define it once, then call it by name whenever you need it. Functions can accept parameters (inputs) and return a value.

// Declaring a function
function greet(name) {
  return "Hello, " + name + "!";
}

console.log(greet("Alice"));
console.log(greet("Bob"));

// Arrow function — shorter syntax, same idea
const multiply = (a, b) => a * b;

console.log(multiply(4, 5)); // 20

// Functions can work with arrays
const prices = [10, 25, 8, 40, 15];

// Find the total using a loop
let total = 0;
for (let price of prices) {
  total += price;
}
console.log("Total: $" + total);

// Or use built-in array methods
let alsoTotal = prices.reduce((sum, price) => sum + price, 0);
console.log("Total: $" + alsoTotal);
Arrow functions (() => {}) are a shorter way to write a function. They behave the same as regular functions in most situations. You will see both styles in real-world code.

7. Connecting JavaScript to the Page

Everything above runs JavaScript in isolation. In a web page, JavaScript's main job is to respond to user actions and update the page. You do this with the DOM (Document Object Model) — JavaScript's interface for reading and changing HTML.

  • document.getElementById("id") — finds an element by its id attribute
  • element.textContent — reads or sets the text inside an element
  • element.addEventListener("click", function) — runs a function when the user clicks
// This example is meant to run in CodePen with an HTML panel.
// Add this to your HTML panel first:
// <button id="btn">Click me</button>
// <p id="output"></p>

let button = document.getElementById("btn");
let output = document.getElementById("output");
let clickCount = 0;

button.addEventListener("click", function () {
  clickCount++;
  output.textContent = "You clicked " + clickCount + " time(s).";
});

To try this in CodePen: paste the HTML comment's code into the HTML panel and the JavaScript into the JS panel, then click the button in the preview.

Project: Price Calculator

We're going to start building a simple JS-powered price calculator. We will build our project locally. Over the next few weeks, we will learn how to track changes to this program with Git and convert it into a WordPress plugin that can be used on our site.

What does it mean to work locally?

Instead of using FileZilla to connect to a remote server, download the files, edit them, and then reupload and refresh the page, we can work with files directly on our computer. This is called working "locally" (as opposed to "remotely") and speeds up the development process.

To get started, open up VScode. If you don't have the LiveServer extension installed - install it now. Go to your Extensions tab, search for "LiveServer", and click "Install".

Next, download this starter template: store-calculator.zip

Extract the files and drag the entire folder into VScode.

Or copy the files one by one: