Lesson 2: Coding Essential Logic

Lesson 2: Coding Essential Logic

Lesson 2: Coding Essential Logic

Unit 5: Building Your Application

The “Brain” of Your App: Coding Logic

Coding logic is the set of rules that tells your application what to do and when to do it. While UI (Lesson 1) is about what the user sees, **logic** is about how the app “thinks” and behaves. It’s the **brain** of your program. All web apps are built on three fundamental pillars of logic:

  • Variables: A way to store and label information.
  • Conditionals: A way to make decisions in your code.
  • Lists/Arrays: A way to store a collection of data.

Let’s explore each of these in more detail with some hands-on activities!

Variables: The Storage Boxes of Code

A variable is like a storage container for a specific piece of information. You give the container a name, and you can put different types of data inside it. The three most common types are:

  • Numbers: For any numerical values, like `10`, `3.14`, or `-5`.
  • Strings: For text, like `”Hello World”`, `”My name is John”`, or `”123 Main Street”`. A string is always enclosed in “quotes”.
  • Booleans: For a simple “yes” or “no” value. This can only be `true` or `false`.

In JavaScript, you declare a variable using `let` or `const`. For example, `let userName = “Alice”;` or `const MAX_SCORE = 100;`.

Conditionals: Making Decisions with `if` and `else`

Conditionals are how your code makes choices. They check if a certain condition is `true` or `false` and then run a specific block of code based on the result. The most common form is the **`if…else if…else`** statement.

The code inside the first `if` statement will only run if its condition is **true**. If it’s **false**, the code moves on to check the next `else if` condition. If none of the `if` or `else if` conditions are true, the code inside the final `else` statement will run. This creates a logical flow of control for your app.

The number guessing game below is a perfect example. We’ll use **conditionals** to check if your guess is too high, too low, or just right.

Activity 1: The Number Guessing Game

A random number has been chosen between 1 and 10. Enter your guess and see if you’re right!

Enter a number and click “Submit Guess” to start.

Lists/Arrays: Storing Collections of Data

An **array** (the term we use in JavaScript) is a special type of variable that can hold multiple values in a single, ordered list. Each item in the list is given a unique number, or **index**, starting from 0.

For example, in the array `let fruits = [“apple”, “banana”, “cherry”];`, the item `”apple”` is at index 0, `”banana”` is at index 1, and `”cherry”` is at index 2. This makes it easy to manage and access multiple related pieces of data.

The shopping list manager below uses an array to store and display all of your items.

Activity 2: The Shopping List Manager