INF-250: Web Design and Development — Arrays, Objects, and Operators

Quick Review: Variables and Data Types

Before diving into arrays and objects, remember these key ideas from the last lesson:

  • Declaring variables:
    Use const by default, and use let only when a value needs to change.
  • Variable naming:
    Choose clear variable names that follow one naming style (usually camelCase in JavaScript).
  • Data types:
    JavaScript values have types like string, number, boolean, null, and undefined.
  • Scope:
    Scope controls where variables can be used. Global variables are defined outside of a function and can be used anywhere. Local variables are defined inside a function and can only be used within that function.
  • Comparing vs Assigning:
    Use == and === to compare values, and = to assign values.

Arrays: Storing Lists of Data

An array is a single variable that stores multiple values in order.

Think of it like a list of values. The list can contain all the same type of data (like numbers) or a mix of different types (like strings, numbers, and booleans).

When to Use an Array

Use an array when you have a collection of related items, such as a list of tasks, student names, quiz scores, or courses.

const todayTasks = [
	"Read chapter",
	"Complete lab",
	"Submit assignment",
];

// Arrays are useful when you have a list of related items
console.log(todayTasks);

How to Declare an Array

Create arrays with square brackets [] and separate values with commas.

const myData = []; // empty array
const colors = ["red", "green", "blue"]; // strings
const scores = [98, 87, 91]; // numbers
const mixed = ["INF-250", 24, true]; //mixed

console.log(colors); // ["red", "green", "blue"]

Accessing Values by Index

Each array item has a position called an index. In JavaScript, indexes start at 0.

const colors = ["red", "green", "blue"];

console.log(colors[0]); // "red"
console.log(colors[1]); // "green"
console.log(colors[2]); // "blue"

// Indexes start at 0 in JavaScript arrays

Updating an Array

You can add new values with push(), update existing values by index, and check total items with length.

const colors = ["red", "green", "blue"];

colors.push("purple"); // add to the end

colors.unshift("yellow"); // add to the beginning

colors[1] = "lime"; // change an existing value

console.log(colors.length); // print the number of items in the array (4)

Looping Through an Array

After updating an array, you will often want to run through every item to display it, check it, or process it.

const colors = ["yellow", "lime", "blue", "purple"];

// for...of gives you each value
for (const color of colors) {
	console.log(color);
}

Objects: Storing Related Data

An object stores related data as key/value pairs.

Think of an object like a profile card for one thing (one student, one course, one product) with multiple details.

When to Use an Object

Use an object when you need to store different pieces of information about one item.

const student = {
	name: "Avery",
	age: 20,
	major: "Computer Science",
};

// Objects are useful for one thing with multiple related details
console.log(student);

How to Declare an Object

Create objects with curly braces {}. Each property has a name (key) and value, separated by a colon.

const student = {
	name: "Avery",
	age: 20,
	isActive: true,
};

const course = {
	code: "INF-250",
	title: "Intro to Programming",
};

Accessing Object Properties

Use dot notation for most cases, and bracket notation when the property name is dynamic or stored in a variable.

const student = {
	name: "Avery",
	age: 20,
};

console.log(student.name); // "Avery" (dot notation)
console.log(student["age"]); // 20 (bracket notation)

Updating an Object

You can update existing properties and add new ones by assigning values to property names.

const student = {
	name: "Avery",
	age: 20,
};

student.age = 21; // update an existing property
student.major = "Design"; // add a new property

console.log(student);
// { name: "Avery", age: 21, major: "Design" }

Operators: How They Work

An operator is a symbol that performs an action on values. For example, some operators do math, while others compare values.

Basic Math Operators

Use operators like +, -, *, /, and % to calculate new values.

const a = 10;
const b = 3;

console.log(a + b); // 13  (addition)
console.log(a - b); // 7   (subtraction)
console.log(a * b); // 30  (multiplication)
console.log(a / b); // 3.333... (division)
console.log(a % b); // 1   (remainder)

let count = 5;
count++; // increment by 1
count--; // decrement by 1
count += 5; // add 5 to count
count -= 2; // subtract 2 from count

Comparison and Equality Operators

Comparison operators like < and > return true or false. Equality operators compare whether values match.

console.log(10 > 5);  // true
console.log(10 < 5);  // false
console.log(10 >= 10); // true
console.log(9 <= 8);  // false

console.log(5 == "5");  // true  (loose equality, type conversion)
console.log(5 === "5"); // false (strict equality, no conversion)

console.log(7 != "7");  // false (loose not-equal)
console.log(7 !== "7"); // true  (strict not-equal)

Use strict operators (=== and !==) whenever possible to avoid automatic type conversion surprises.

The + Operator with Strings

The + operator can either add numbers or join strings together (concatenation), depending on the values.

console.log("Hello" + " " + "World"); // "Hello World"
console.log("Score: " + 42);            // "Score: 42"

// + adds numbers, but concatenates strings

prompt()

The prompt() function shows a dialog box that asks the user for input. It always returns a string, so you may need to convert it to a number if you want to do math with it.

You can save it to a variable for later use:

const name = prompt("What is your name?");
console.log("Hello, " + name + "!");

Group work

Profile Builder: https://padams-msj.github.io/profile-builder/
Repository: https://github.com/padams-msj/profile-builder

Copy this code to your computer and open it in VScode.

It contains a partially-built profile builder. Improve it!

  • Complete the checkIfComplete() function so that to page displays a message when all questions have been answered.
  • Add some more questions to the builder and update the variables accordingly.
  • Improve the HTML and add CSS.
  • Maybe this is a chatty profile builder? Add some feedback, for example if the user's age is above 30 display a message saying "wow ur old." Or if the favorite color is "red", display a message saying "red is the best color!" - or figure out a way to compliment whatever color is entered.
Prompts always return strings!
If you want to do something with the age entered by the user, you will need to convert it to a number first. You can do this with the Number() function, like this: const age = Number(prompt('What is your age?'))