updating part 2

softchris-patch-9
chris 2 months ago
parent 5bac96af11
commit 62a6a5377e

@ -3,6 +3,12 @@
![JavaScript Basics - Data types](../../sketchnotes/webdev101-js-datatypes.png)
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
Data types are the foundation of all programming languages, and JavaScript is no exception. Think of data types as the different kinds of information your programs can work with just like how you might organize different types of items in your home, JavaScript organizes different types of data in specific ways. Understanding data types will help you write more reliable code and avoid common beginner mistakes.
In this lesson, you'll discover the core data types that JavaScript provides and learn how to work with each one effectively. You'll explore variables as containers for your data, understand how to perform operations with different types, and see how JavaScript handles the relationships between them. This knowledge forms the building blocks for everything else you'll learn in web development.
By the end of this lesson, you'll confidently work with numbers, text, true/false values, and understand when and why to use each type. You'll also learn about JavaScript's unique behaviors with data types that make it both powerful and occasionally surprising. Let's dive into the fundamental data structures that power modern web applications!
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/)
@ -17,16 +23,21 @@ This lesson covers the basics of JavaScript, the language that provides interact
> 🎥 Click the images above for videos about variables and data types
Let's start with variables and the data types that populate them!
## Variables
Variables are like labeled containers that hold different types of information in your programs. Just as you might use labeled boxes to organize items in your home, variables help you organize and manage data in your code. They're essential because they allow you to store information, change it when needed, and use it throughout your program.
Let's explore how to create variables and see them in action. You'll learn the modern way to declare variables and understand why certain keywords are preferred over others.
Variables store values that can be used and changed throughout your code.
Creating and **declaring** a variable has the following syntax **[keyword] [name]**. It's made up of the two parts:
- **Keyword**. Keywords can be `let` or `var`.
- **Keyword**. Use `let` for variables that can change, or `const` for values that stay the same.
- **The variable name**, this is a descriptive name you choose yourself.
✅ The keyword `let` was introduced in ES6 and gives your variable a so called _block scope_. It's recommended that you use `let` over `var`. We will cover block scopes more in depth in future parts.
- **The variable name**, this is a name you choose yourself.
✅ The keyword `let` was introduced in ES6 and gives your variable a so called _block scope_. It's recommended that you use `let` or `const` instead of the older `var` keyword. We will cover block scopes more in depth in future parts.
### Task - working with variables
@ -36,7 +47,10 @@ Creating and **declaring** a variable has the following syntax **[keyword] [name
let myVariable;
```
`myVariable` has now been declared using the `let` keyword. It currently doesn't have a value.
**Here's what this code does:**
- **Creates** a variable named `myVariable` using the `let` keyword
- **Reserves** space in memory for storing a value
- **Leaves** the variable undefined until we assign it a value
1. **Assign a value**. Store a value in a variable with the `=` operator, followed by the expected value.
@ -44,9 +58,12 @@ Creating and **declaring** a variable has the following syntax **[keyword] [name
myVariable = 123;
```
> Note: the use of `=` in this lesson means we make use of an "assignment operator", used to set a value to a variable. It doesn't denote equality.
**Breaking down what happens here:**
- **Uses** the assignment operator `=` to store a value
- **Assigns** the number 123 to our previously declared variable
- **Initializes** the variable with its first actual value
`myVariable` has now been *initialized* with the value 123.
> Note: the use of `=` in this lesson means we make use of an "assignment operator", used to set a value to a variable. It doesn't denote equality.
1. **Refactor**. Replace your code with the following statement.
@ -54,7 +71,10 @@ Creating and **declaring** a variable has the following syntax **[keyword] [name
let myVariable = 123;
```
The above is called an _explicit initialization_ when a variable is declared and is assigned a value at the same time.
**In the above, we've:**
- **Combined** declaration and initialization into one line
- **Created** what's called an _explicit initialization_
- **Streamlined** our code by doing both steps at once
1. **Change the variable value**. Change the variable value in the following way:
@ -62,63 +82,106 @@ Creating and **declaring** a variable has the following syntax **[keyword] [name
myVariable = 321;
```
Once a variable is declared, you can change its value at any point in your code with the `=` operator and the new value.
**What you need to know:**
- **Updates** the variable's value from 123 to 321
- **Overwrites** the previous value completely
- **Demonstrates** that `let` variables can be reassigned
✅ Try it! You can write JavaScript right in your browser. Open a browser window and navigate to Developer Tools. In the console, you will find a prompt; type `let myVariable = 123`, press return, then type `myVariable`. What happens? Note, you'll learn more about these concepts in subsequent lessons.
## Constants
Constants are special variables that can't be changed once you set their value. Think of them like permanent labels once you write on them, they stay that way. Constants are incredibly useful for storing values that you know will never change throughout your program, like mathematical constants or configuration settings.
Using constants helps prevent accidental changes to important values and makes your code more reliable and easier to understand.
Declaration and initialization of a constant follows the same concepts as a variable, with the exception of the `const` keyword. Constants are typically declared with all uppercase letters.
```javascript
const MY_VARIABLE = 123;
```
**Here's what this code does:**
- **Creates** a constant named `MY_VARIABLE` with the value 123
- **Uses** uppercase naming convention for constants
- **Prevents** any future changes to this value
Constants are similar to variables, with two exceptions:
- **Must have a value**. Constants must be initialized, or an error will occur when running code.
- **Reference cannot be changed**. The reference of a constant cannot be changed once initialized, or an error will occur when running code. Let's look at two examples:
- **Simple value**. The following is NOT allowed:
- **Reference cannot be changed**. The reference of a constant cannot be changed once initialized, or an error will occur when running code. Let's look at examples:
**Simple value** - The following is NOT allowed:
```javascript
const PI = 3;
PI = 4; // not allowed
```
**What you need to remember:**
- **Attempts** to reassign a constant will cause an error
- **Protects** important values from accidental changes
- **Ensures** the value remains consistent throughout your program
- **Object reference is protected**. The following is NOT allowed.
**Object reference is protected** - The following is NOT allowed:
```javascript
const obj = { a: 3 };
obj = { b: 5 } // not allowed
```
- **Object value is not protected**. The following IS allowed:
**Understanding these concepts:**
- **Prevents** replacing the entire object with a new one
- **Protects** the reference to the original object
- **Maintains** the object's identity in memory
**Object value is not protected** - The following IS allowed:
```javascript
const obj = { a: 3 };
obj.a = 5; // allowed
```
Above you are changing the value of the object but not the reference itself, which makes it allowed.
**Breaking down what happens here:**
- **Modifies** the property value inside the object
- **Keeps** the same object reference
- **Demonstrates** that object contents can change while the reference stays constant
> Note, a `const` means the reference is protected from reassignment. The value is not _immutable_ though and can change, especially if it's a complex construct like an object.
## Data Types
Data types are JavaScript's way of categorizing different kinds of information. Just like how you might sort items in your home into categories like books, tools, or clothing, JavaScript sorts data into specific types like numbers, text, or true/false values. Each type has its own special properties and behaviors that make it perfect for certain tasks.
Understanding data types is crucial because it helps you choose the right tool for each job and avoid common programming mistakes. When you know what type of data you're working with, you can predict how it will behave and what operations you can perform on it.
Variables can store many different types of values, like numbers and text. These various types of values are known as the **data type**. Data types are an important part of software development because it helps developers make decisions on how the code should be written and how the software should run. Furthermore, some data types have unique features that help transform or extract additional information in a value.
✅ Data Types are also referred to as JavaScript data primitives, as they are the lowest-level data types that are provided by the language. There are 7 primitive data types: string, number, bigint, boolean, undefined, null and symbol. Take a minute to visualize what each of these primitives might represent. What is a `zebra`? How about `0`? `true`?
### Numbers
In the previous section, the value of `myVariable` was a number data type.
Numbers in JavaScript are incredibly versatile and handle both whole numbers (integers) and decimal numbers (floats) seamlessly. Unlike some programming languages that treat these as separate types, JavaScript simplifies things by using one number type for everything mathematical.
`let myVariable = 123;`
In the previous section, the value of `myVariable` was a number data type:
```javascript
let myVariable = 123;
```
**Here's what this code does:**
- **Stores** the integer value 123 in the variable
- **Uses** JavaScript's number data type automatically
- **Prepares** the variable for mathematical operations
Variables can store all types of numbers, including decimals or negative numbers. Numbers also can be used with arithmetic operators, covered in the [next section](#arithmetic-operators).
### Arithmetic Operators
Arithmetic operators are the mathematical symbols that let you perform calculations with your numbers. Think of them as the basic math operations you learned in school, but now you can use them to make your programs dynamic and interactive.
These operators work exactly like you'd expect from mathematics, and they're essential for creating calculations, animations, game scores, and countless other programming tasks.
There are several types of operators to use when performing arithmetic functions, and some are listed here:
| Symbol | Description | Example |
@ -133,16 +196,32 @@ There are several types of operators to use when performing arithmetic functions
### Strings
Strings are how JavaScript handles text data everything from single letters to entire paragraphs. Think of strings as any piece of text that you want to display, store, or manipulate in your programs. They're called "strings" because they're essentially strings of characters linked together.
Strings are everywhere in web development: user names, messages, button labels, error notifications, and much more. Learning to work with strings effectively is essential for creating interactive web applications.
Strings are sets of characters that reside between single or double quotes.
- `'This is a string'`
- `"This is also a string"`
- `let myString = 'This is a string value stored in a variable';`
```javascript
'This is a string'
"This is also a string"
let myString = 'This is a string value stored in a variable';
```
**Understanding these concepts:**
- **Uses** either single quotes `'` or double quotes `"` to define strings
- **Stores** text data that can include letters, numbers, and symbols
- **Assigns** string values to variables for later use
- **Requires** quotes to distinguish text from variable names
Remember to use quotes when writing a string, or else JavaScript will assume it's a variable name.
### Formatting Strings
Working with strings often means combining them, inserting variables, or arranging them in specific ways. Just like how you might combine words to form sentences, JavaScript provides several methods to format and manipulate strings to create the exact text you need.
String formatting is essential for creating dynamic content like personalized messages, formatted displays, and interactive user interfaces.
Strings are textual, and will require formatting from time to time.
To **concatenate** two or more strings, or join them together, use the `+` operator.
@ -154,9 +233,14 @@ let myString2 = "World";
myString1 + myString2 + "!"; //HelloWorld!
myString1 + " " + myString2 + "!"; //Hello World!
myString1 + ", " + myString2 + "!"; //Hello, World!
```
**Step by step, here's what's happening:**
- **Combines** multiple strings using the `+` operator
- **Joins** strings directly together without spaces in the first example
- **Adds** space characters `" "` between strings for readability
- **Inserts** punctuation like commas to create proper formatting
✅ Why does `1 + 1 = 2` in JavaScript, but `'1' + '1' = 11?` Think about it. What about `'1' + 1`?
**Template literals** are another way to format strings, except instead of quotes, the backtick is used. Anything that is not plain text must be placed inside placeholders `${ }`. This includes any variables that may be strings.
@ -169,21 +253,47 @@ let myString2 = "World";
`${myString1}, ${myString2}!` //Hello, World!
```
**Let's understand each part:**
- **Uses** backticks `` ` `` instead of regular quotes to create template literals
- **Embeds** variables directly using `${}` placeholder syntax
- **Preserves** spaces and formatting exactly as written
- **Provides** a cleaner way to create complex strings with variables
You can achieve your formatting goals with either method, but template literals will respect any spaces and line breaks.
✅ When would you use a template literal vs. a plain string?
### Booleans
Booleans represent the simplest form of data: something is either true or false, yes or no, on or off. Named after mathematician George Boole, these values are fundamental to how computers make decisions and control program flow.
Booleans are incredibly powerful despite their simplicity. They're the foundation of all conditional logic in programming every "if this, then that" decision your program makes relies on Boolean values.
Booleans can be only two values: `true` or `false`. Booleans can help make decisions on which lines of code should run when certain conditions are met. In many cases, [operators](#arithmetic-operators) assist with setting the value of a Boolean and you will often notice and write variables being initialized or their values being updated with an operator.
- `let myTrueBool = true`
- `let myFalseBool = false`
```javascript
let myTrueBool = true;
let myFalseBool = false;
```
**In the above, we've:**
- **Created** a variable that stores the Boolean value `true`
- **Demonstrated** how to store the Boolean value `false`
- **Used** the exact keywords `true` and `false` (no quotes needed)
- **Prepared** these variables for use in conditional statements
✅ A variable can be considered 'truthy' if it evaluates to a boolean `true`. Interestingly, in JavaScript, [all values are truthy unless defined as falsy](https://developer.mozilla.org/docs/Glossary/Truthy).
---
## GitHub Copilot Agent Challenge 🚀
Use the Agent mode to complete the following challenge:
**Description:** Create a personal information manager that demonstrates all the JavaScript data types you've learned in this lesson while handling real-world data scenarios.
**Prompt:** Build a JavaScript program that creates a user profile object containing: a person's name (string), age (number), is a student status (boolean), favorite colors as an array, and an address object with street, city, and zip code properties. Include functions to display the profile information and update individual fields. Make sure to demonstrate string concatenation, template literals, arithmetic operations with the age, and boolean logic for the student status.
## 🚀 Challenge
JavaScript is notorious for its surprising ways of handling datatypes on occasion. Do a bit of research on these 'gotchas'. For example: case sensitivity can bite! Try this in your console: `let age = 1; let Age = 2; age == Age` (resolves `false` -- why?). What other gotchas can you find?

@ -1,11 +1,87 @@
# Data Types Practice
# Data Types Practice: E-commerce Shopping Cart
## Instructions
Imagine you are building a shopping cart. Write documentation on the data types you would need to complete your shopping experience. For each data type, explain how and why you would use it, and provide an example. The six JavaScript data types are: String, Number, Boolean, Null, Undefined, and Object.
Imagine you are building a modern e-commerce shopping cart system. This assignment will help you understand how different JavaScript data types work together to create real-world applications.
### Your Task
Create a comprehensive analysis of how you would use JavaScript data types in a shopping cart application. For each of the seven primitive data types and objects, you need to:
1. **Identify** the data type and its purpose
2. **Explain** why this data type is the best choice for specific shopping cart features
3. **Provide** realistic code examples showing the data type in action
4. **Describe** how this data type interacts with other parts of the shopping cart
### Required Data Types to Cover
**Primitive Data Types:**
- **String**: Product names, descriptions, user information
- **Number**: Prices, quantities, tax calculations
- **Boolean**: Item availability, user preferences, cart status
- **Null**: Intentionally empty values (like missing discount codes)
- **Undefined**: Uninitialized values or missing data
- **Symbol**: Unique identifiers (advanced use)
- **BigInt**: Large financial calculations (advanced use)
**Reference Types:**
- **Object**: Product details, user profiles, cart contents
- **Array**: List of products, order history, categories
### Example Format for Each Data Type
For each data type, structure your response like this:
```markdown
## [Data Type Name]
**Purpose in Shopping Cart:** [Explain what this data type does]
**Why This Type:** [Explain why this is the best choice]
**Code Example:**
```javascript
// Your realistic code example here
```
**Real-world Usage:** [Describe how this would work in practice]
**Interactions:** [Explain how this data type works with others]
```
### Bonus Challenges
1. **Type Coercion**: Show an example where JavaScript automatically converts between data types in your shopping cart (e.g., string "5" + number 10)
2. **Data Validation**: Demonstrate how you would check if user input is the correct data type before processing
3. **Performance Considerations**: Explain when you might choose one data type over another for performance reasons
### Submission Guidelines
- Create a markdown document with clear headings for each data type
- Include working JavaScript code examples
- Use realistic e-commerce scenarios in your examples
- Explain your reasoning clearly for beginners to understand
- Test your code examples to ensure they work correctly
## Rubric
Criteria | Exemplary | Adequate | Needs Improvement
--- | --- | --- | -- |
Data Types | All six data types are listed, explored in detail, and documented with examples | Four data types are explored with some explanation | Two data types are explored with minimal explanation |
| Criteria | Exemplary (90-100%) | Proficient (80-89%) | Developing (70-79%) | Needs Improvement (Below 70%) |
|----------|---------------------|---------------------|---------------------|------------------------------|
| **Data Type Coverage** | All 7 primitive types and objects/arrays covered with detailed explanations | 6-7 data types covered with good explanations | 4-5 data types covered with basic explanations | Fewer than 4 data types or minimal explanations |
| **Code Examples** | All examples are realistic, working, and well-commented | Most examples work and are relevant to e-commerce | Some examples work but may be generic | Code examples are incomplete or non-functional |
| **Real-world Application** | Clearly connects each data type to practical shopping cart features | Good connection to e-commerce scenarios | Some connection to shopping cart context | Limited real-world application demonstrated |
| **Technical Accuracy** | All technical information is correct and demonstrates deep understanding | Most technical information is accurate | Generally accurate with minor errors | Contains significant technical errors |
| **Communication** | Explanations are clear, beginner-friendly, and well-organized | Good explanations that are mostly clear | Explanations are understandable but may lack clarity | Explanations are unclear or poorly organized |
| **Bonus Elements** | Includes multiple bonus challenges with excellent execution | Includes one or more bonus challenges well done | Attempts bonus challenges with mixed success | No bonus challenges attempted |
### Learning Objectives
By completing this assignment, you will:
- ✅ **Understand** the seven JavaScript primitive data types and their uses
- ✅ **Apply** data types to real-world programming scenarios
- ✅ **Analyze** when to choose specific data types for different purposes
- ✅ **Create** working code examples that demonstrate data type usage
- ✅ **Explain** technical concepts in beginner-friendly language
- ✅ **Connect** fundamental programming concepts to practical applications

@ -6,7 +6,11 @@
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app)
When we think about writing code, we always want to ensure our code is readable. While this sounds counterintuitive, code is read many more times than it's written. One core tool in a developer's toolbox to ensure maintainable code is the **function**.
Functions are the building blocks of modern JavaScript programming and one of the most powerful concepts you'll master as a web developer. They allow you to package code into reusable blocks, making your programs more organized, efficient, and easier to maintain. Think of functions as specialized tools in your programming toolkit each one designed to accomplish a specific task whenever you need it.
In this lesson, you'll discover how to create your own functions, pass information to them, and get meaningful results back. You'll learn the difference between functions and methods, explore various ways to write functions (including modern arrow function syntax), and understand how functions can accept other functions as parameters. These concepts form the foundation for writing clean, professional JavaScript code.
By the end of this lesson, you'll be confidently creating functions that solve real-world problems and understanding how they fit into the bigger picture of web development. Let's dive in and unlock these fundamental programming concepts together!
[![Methods and Functions](https://img.youtube.com/vi/XgKsD6Zwvlc/0.jpg)](https://youtube.com/watch?v=XgKsD6Zwvlc "Methods and Functions")
@ -16,12 +20,16 @@ When we think about writing code, we always want to ensure our code is readable.
## Functions
Now that you understand why functions are essential, let's explore what they actually are and how they work. A function is like a mini-program within your larger program a self-contained block of code that performs a specific task.
At its core, a function is a block of code we can execute on demand. This is perfect for scenarios where we need to perform the same task multiple times; rather than duplicating the logic in multiple locations (which would make it hard to update when the time comes), we can centralize it in one location, and call it whenever we need the operation performed - you can even call functions from other functions!.
Just as important is the ability to name a function. While this might seem trivial, the name provides a quick way of documenting a section of code. You could think of this as a label on a button. If I click on a button which reads "Cancel timer", I know it's going to stop running the clock.
## Creating and calling a function
Let's create your first function together! We'll start with the basic syntax and build up to more complex examples as your confidence grows.
The syntax for a function looks like the following:
```javascript
@ -30,6 +38,13 @@ function nameOfFunction() { // function definition
}
```
**Here's what this code structure includes:**
- **Uses** the `function` keyword to declare a new function
- **Provides** a descriptive name for the function (`nameOfFunction`)
- **Contains** parentheses `()` where parameters can be added later
- **Wraps** the function body in curly braces `{}`
- **Includes** comments to help identify the different parts
If I wanted to create a function to display a greeting, it might look like this:
```javascript
@ -38,6 +53,12 @@ function displayGreeting() {
}
```
**Breaking down what happens here:**
- **Defines** a function named `displayGreeting` with no parameters
- **Uses** `console.log()` to output a message to the browser's developer console
- **Contains** the string `'Hello, world!'` as the message to display
- **Creates** a reusable block of code that can be called multiple times
Whenever we want to call (or invoke) our function, we use the name of the function followed by `()`. It's worth noting the fact our function can be defined before or after we decide to call it; the JavaScript compiler will find it for you.
```javascript
@ -45,7 +66,13 @@ Whenever we want to call (or invoke) our function, we use the name of the functi
displayGreeting();
```
> **NOTE:** There is a special type of function known as a **method**, which you've already been using! In fact, we saw this in our demo above when we used `console.log`. What makes a method different from a function is a method is attached to an object (`console` in our example), while a function is free floating. You will hear many developers use these terms interchangeably.
**What this function call accomplishes:**
- **Executes** the code inside the `displayGreeting` function
- **Displays** "Hello, world!" in the browser console
- **Demonstrates** how to invoke a function using its name and parentheses
- **Shows** that functions can be called multiple times throughout your code
> **NOTE:** There is a special type of function known as a **method**, which you've already been using! In fact, we saw this in our demo above when we used `console.log()`. What makes a method different from a function is a method is attached to an object (`console` in our example), while a function is free floating. You will hear many developers use these terms interchangeably.
### Function best practices
@ -57,6 +84,8 @@ There are a handful of best practices to keep in mind when creating functions
## Passing information to a function
Our current `displayGreeting` function works, but it's quite limited it can only say "Hello, world!" to everyone. Let's make it more flexible and personal by learning how to pass information into functions.
To make a function more reusable you'll often want to pass information into it. If we consider our `displayGreeting` example above, it will only display **Hello, world!**. Not the most useful function one could create. If we want to make it a little more flexible, like allowing someone to specify the name of the person to greet, we can add a **parameter**. A parameter (also sometimes called an **argument**), is additional information sent to a function.
Parameters are listed in the definition part within parenthesis and are comma separated like so:
@ -67,6 +96,12 @@ function name(param, param2, param3) {
}
```
**Understanding these concepts:**
- **Lists** parameters inside the parentheses, separated by commas
- **Accepts** multiple pieces of information (param, param2, param3)
- **Creates** placeholders that will hold the actual values when the function is called
- **Allows** the same function to work with different data each time
We can update our `displayGreeting` to accept a name and have that displayed.
```javascript
@ -76,6 +111,12 @@ function displayGreeting(name) {
}
```
**In the above, we've:**
- **Added** a `name` parameter to receive the person's name
- **Created** a template literal using backticks and `${}` syntax for string interpolation
- **Stored** the personalized message in a `const` variable called `message`
- **Displayed** the customized greeting using `console.log()`
When we want to call our function and pass in the parameter, we specify it in the parenthesis.
```javascript
@ -83,8 +124,16 @@ displayGreeting('Christopher');
// displays "Hello, Christopher!" when run
```
**Step by step, here's what's happening:**
- **Calls** the `displayGreeting` function with the string `'Christopher'`
- **Passes** the name as an argument to the `name` parameter
- **Substitutes** `'Christopher'` into the template literal
- **Outputs** "Hello, Christopher!" to the console
## Default values
Sometimes you want to make parameters optional by providing sensible defaults. This makes your functions more flexible and easier to use.
We can make our function even more flexible by adding more parameters. But what if we don't want to require every value be specified? Keeping with our greeting example, we could leave name as required (we need to know who we're greeting), but we want to allow the greeting itself to be customized as desired. If someone doesn't want to customize it, we provide a default value instead. To provide a default value to a parameter, we set it much in the same way we set a value for a variable - `parameterName = 'defaultValue'`. To see a full example:
```javascript
@ -93,6 +142,12 @@ function displayGreeting(name, salutation='Hello') {
}
```
**Key points to remember:**
- **Defines** `name` as a required parameter (no default value)
- **Sets** `salutation` with a default value of `'Hello'`
- **Uses** the assignment operator `=` to specify the default
- **Allows** the function to work with just one argument or both
When we call the function, we can then decide if we want to set a value for `salutation`.
```javascript
@ -103,8 +158,16 @@ displayGreeting('Christopher', 'Hi');
// displays "Hi, Christopher"
```
**What you need to know:**
- **Uses** the default value `'Hello'` when only the name is provided
- **Overrides** the default with `'Hi'` when both parameters are specified
- **Demonstrates** how optional parameters make functions more flexible
- **Shows** that required parameters come before optional ones
## Return values
So far, our functions have only displayed messages, but often you'll want functions to calculate something and give you back a result that you can use in other parts of your code.
Up until now the function we built will always output to the [console](https://developer.mozilla.org/docs/Web/API/console). Sometimes this can be exactly what we're looking for, especially when we create functions which will be calling other services. But what if I want to create a helper function to perform a calculation and provide the value back so I can use it elsewhere?
We can do this by using a **return value**. A return value is returned by the function, and can be stored in a variable just the same as we could store a literal value such as a string or number.
@ -113,7 +176,13 @@ If a function does return something then the keyword `return` is used. The `retu
```javascript
return myVariable;
```
```
**Understanding these concepts:**
- **Uses** the `return` keyword to send a value back to the caller
- **Ends** function execution immediately when the return statement runs
- **Allows** the returned value to be stored in a variable or used directly
- **Provides** a way for functions to produce results rather than just side effects
We could create a function to create a greeting message and return the value back to the caller
@ -124,14 +193,28 @@ function createGreetingMessage(name) {
}
```
**Breaking down what happens here:**
- **Creates** a personalized message using template literal syntax
- **Stores** the message in a `const` variable for clarity
- **Returns** the message string to whoever called the function
- **Allows** the calling code to use the result however it needs
When calling this function we'll store the value in a variable. This is much the same way we'd set a variable to a static value (like `const name = 'Christopher'`).
```javascript
const greetingMessage = createGreetingMessage('Christopher');
```
**What this accomplishes:**
- **Calls** the `createGreetingMessage` function with `'Christopher'` as the argument
- **Receives** the returned string "Hello, Christopher"
- **Stores** the result in the `greetingMessage` variable
- **Makes** the greeting message available for use elsewhere in the code
## Functions as parameters for functions
One of the most powerful features in JavaScript is the ability to pass functions to other functions. This might sound complex, but it's actually a pattern you'll use frequently in modern web development.
As you progress in your programming career, you will come across functions which accept functions as parameters. This neat trick is commonly used when we don't know when something is going to occur or complete, but we know we need to perform an operation in response.
As an example, consider [setTimeout](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout), which begins a timer and will execute code when it completes. We need to tell it what code we want to execute. Sounds like a perfect job for a function!
@ -146,8 +229,16 @@ function displayDone() {
setTimeout(displayDone, 3000);
```
**Here's what this code does:**
- **Defines** a function called `displayDone` that logs a message
- **Uses** `setTimeout()` to schedule the function to run later
- **Passes** the function name (without parentheses) as the first parameter
- **Sets** the delay to 3000 milliseconds (3 seconds)
### Anonymous functions
Sometimes you need a function for just one specific purpose and don't want to clutter your code with extra function names. JavaScript provides a perfect solution for this scenario.
Let's take another look at what we've built. We're creating a function with a name which will be used one time. As our application gets more complex, we can see ourselves creating a lot of functions which will only be called once. This isn't ideal. As it turns out, we don't always need to provide a name!
When we are passing a function as a parameter we can bypass creating one in advance and instead build one as part of the parameter. We use the same `function` keyword, but instead we build it as a parameter.
@ -160,10 +251,18 @@ setTimeout(function() {
}, 3000);
```
**In the above, we've:**
- **Created** a function directly inside the `setTimeout` call
- **Eliminated** the need for a separate function declaration
- **Used** the `function` keyword without a name
- **Achieved** the same result with less code
If you run our new code you'll notice we get the same results. We've created a function, but didn't have to give it a name!
### Fat arrow functions
Modern JavaScript provides an even more concise way to write functions using arrow syntax. This is a popular and widely-used feature in contemporary web development.
One shortcut common in a lot of programming languages (including JavaScript) is the ability to use what's called an **arrow** or **fat arrow** function. It uses a special indicator of `=>`, which looks like an arrow - thus the name! By using `=>`, we are able to skip the `function` keyword.
Let's rewrite our code one more time to use a fat arrow function:
@ -174,6 +273,12 @@ setTimeout(() => {
}, 3000);
```
**What you need to remember:**
- **Uses** parentheses `()` for the parameter list (empty in this case)
- **Includes** the arrow `=>` to indicate this is an arrow function
- **Maintains** the same curly braces `{}` for the function body
- **Provides** a more concise syntax popular in modern JavaScript
### When to use each strategy
You've now seen we have three ways to pass a function as a parameter and might be wondering when to use each. If you know you'll be using the function more than once, create it as normal. If you'll be using it for just the one location, it's generally best to use an anonymous function. Whether or not you use a fat arrow function or the more traditional `function` syntax is up to you, but you will notice most modern developers prefer `=>`.

@ -2,12 +2,65 @@
## Instructions
Create different functions, both functions that return something and functions that don't return anything.
In this assignment, you'll practice creating different types of functions to reinforce the concepts you've learned about JavaScript functions, parameters, default values, and return statements.
See if you can create a function that has a mix of parameters and parameters with default values.
Create a JavaScript file called `functions-practice.js` and implement the following functions:
### Part 1: Basic Functions
1. **Create a function called `sayHello`** that doesn't take any parameters and simply logs "Hello!" to the console.
2. **Create a function called `introduceYourself`** that takes a `name` parameter and logs a message like "Hi, my name is [name]" to the console.
### Part 2: Functions with Default Parameters
3. **Create a function called `greetPerson`** that takes two parameters: `name` (required) and `greeting` (optional, defaults to "Hello"). The function should log a message like "[greeting], [name]!" to the console.
### Part 3: Functions that Return Values
4. **Create a function called `addNumbers`** that takes two parameters (`num1` and `num2`) and returns their sum.
5. **Create a function called `createFullName`** that takes `firstName` and `lastName` parameters and returns the full name as a single string.
### Part 4: Mix It All Together
6. **Create a function called `calculateTip`** that takes two parameters: `billAmount` (required) and `tipPercentage` (optional, defaults to 15). The function should calculate and return the tip amount.
### Part 5: Test Your Functions
Add function calls to test each of your functions and display the results using `console.log()`.
**Example test calls:**
```javascript
// Test your functions here
sayHello();
introduceYourself("Sarah");
greetPerson("Alex");
greetPerson("Maria", "Hi");
const sum = addNumbers(5, 3);
console.log(`The sum is: ${sum}`);
const fullName = createFullName("John", "Doe");
console.log(`Full name: ${fullName}`);
const tip = calculateTip(50);
console.log(`Tip for $50 bill: $${tip}`);
```
## Rubric
| Criteria | Exemplary | Adequate | Needs Improvement |
| -------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ----------------- |
| | Solution is offered with two or more well-performing functions with diverse parameters | Working solution is offered with one function and few parameters | Solution has bugs |
| Criteria | Exemplary | Adequate | Needs Improvement |
| -------- | --------- | -------- | ----------------- |
| **Function Creation** | All 6 functions are correctly implemented with proper syntax and naming conventions | 4-5 functions are correctly implemented with minor syntax issues | 3 or fewer functions implemented or major syntax errors |
| **Parameters & Default Values** | Correctly uses required parameters, optional parameters, and default values as specified | Uses parameters correctly but may have issues with default values | Incorrect or missing parameter implementation |
| **Return Values** | Functions that should return values do so correctly, and functions that shouldn't return values only perform actions | Most return values are correct with minor issues | Significant problems with return statements |
| **Code Quality** | Clean, well-organized code with meaningful variable names and proper indentation | Code works but could be cleaner or better organized | Code is difficult to read or poorly structured |
| **Testing** | All functions are tested with appropriate function calls and results are displayed clearly | Most functions are tested adequately | Limited or incorrect testing of functions |
## Bonus Challenges (Optional)
If you want to challenge yourself further:
1. **Create an arrow function version** of one of your functions
2. **Create a function that accepts another function as a parameter** (like the `setTimeout` examples from the lesson)
3. **Add input validation** to ensure your functions handle invalid inputs gracefully
---
> 💡 **Tip**: Remember to open your browser's developer console (F12) to see the output of your `console.log()` statements!

@ -4,6 +4,12 @@
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
Making decisions is at the heart of programming and mirrors how we think in everyday life. Just as you decide what to wear based on the weather or which route to take based on traffic, your JavaScript programs need to make choices based on different conditions. This fundamental concept transforms static code into dynamic, intelligent applications that can respond to user input and changing circumstances.
In this lesson, you'll discover how to use conditional statements, comparison operators, and logical expressions to control the flow of your programs. You'll learn about `if` statements, `switch` statements, and the powerful logical operators that help your code make smart decisions. These tools will enable you to create programs that can evaluate situations and respond appropriately.
By the end of this lesson, you'll be writing JavaScript that can analyze data, validate user input, and execute different code paths based on various conditions. Let's explore how to give your programs the power of decision-making!
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/11)
@ -18,17 +24,28 @@ Making decisions and controlling the order in which your code runs makes your co
## A Brief Recap on Booleans
Before we dive into decision-making, let's revisit Boolean values from our previous lessons. Booleans are the foundation of all conditional logic in programming they represent the simple concept of "yes or no," "true or false," or "on or off."
Booleans can have only two values: `true` or `false`. Booleans help make decisions on which lines of code should run when certain conditions are met.
Set your boolean to be true or false like this:
`let myTrueBool = true`
`let myFalseBool = false`
```javascript
let myTrueBool = true;
let myFalseBool = false;
```
**Here's what this code does:**
- **Creates** a variable `myTrueBool` and assigns the value `true`
- **Creates** a variable `myFalseBool` and assigns the value `false`
- **Uses** the `let` keyword to declare variables that can be changed later
✅ Booleans are named after the English mathematician, philosopher and logician George Boole (18151864).
## Comparison Operators and Booleans
Now that you understand Boolean values, let's explore how to create them using comparison operators. These operators are your tools for asking questions in code: "Is this number bigger than that one?" or "Are these two values the same?" Understanding these operators is crucial for writing effective conditional statements.
Operators are used to evaluate conditions by making comparisons that will create a Boolean value. The following is a list of operators that are frequently used.
| Symbol | Description | Example |
@ -44,47 +61,69 @@ Operators are used to evaluate conditions by making comparisons that will create
## If Statement
The if statement will run code in between its blocks if the condition is true.
The `if` statement is your first tool for making decisions in JavaScript. Think of it as asking a question if the answer is "yes" (true), then do something specific. This is the foundation of conditional logic and allows your programs to respond intelligently to different situations.
The `if` statement will run code in between its blocks if the condition is true.
```javascript
if (condition) {
//Condition is true. Code in this block will run.
// Condition is true. Code in this block will run.
}
```
**Understanding this structure:**
- **Evaluates** the condition inside the parentheses `()`
- **Executes** the code inside the curly braces `{}` only if the condition is `true`
- **Skips** the code block entirely if the condition is `false`
Logical operators are often used to form the condition.
```javascript
let currentMoney;
let laptopPrice;
let currentMoney = 1000;
let laptopPrice = 800;
if (currentMoney >= laptopPrice) {
//Condition is true. Code in this block will run.
// Condition is true. Code in this block will run.
console.log("Getting a new laptop!");
}
```
**In the above, we've:**
- **Declared** variables for current money and laptop price with realistic values
- **Used** the greater than or equal operator `>=` to compare values
- **Executed** the `console.log()` statement because `1000 >= 800` evaluates to `true`
## If..Else Statement
Sometimes you want your program to do one thing when a condition is true and something different when it's false. The `else` statement provides this "Plan B" it ensures your program always has a response, regardless of whether the initial condition is met.
The `else` statement will run the code in between its blocks when the condition is false. It's optional with an `if` statement.
```javascript
let currentMoney;
let laptopPrice;
let currentMoney = 500;
let laptopPrice = 800;
if (currentMoney >= laptopPrice) {
//Condition is true. Code in this block will run.
// Condition is true. Code in this block will run.
console.log("Getting a new laptop!");
} else {
//Condition is false. Code in this block will run.
// Condition is false. Code in this block will run.
console.log("Can't afford a new laptop, yet!");
}
```
**Breaking down what happens here:**
- **Compares** `currentMoney` (500) with `laptopPrice` (800)
- **Evaluates** the condition `500 >= 800` as `false`
- **Skips** the first code block because the condition failed
- **Executes** the `else` block, displaying "Can't afford a new laptop, yet!"
✅ Test your understanding of this code and the following code by running it in a browser console. Change the values of the currentMoney and laptopPrice variables to change the returned `console.log()`.
## Switch Statement
When you need to compare a single value against multiple possible options, the `switch` statement provides a cleaner alternative to multiple `if..else` statements. Think of it like a restaurant menu where you pick one option from many choices the `switch` statement makes this type of decision-making more readable and organized.
The `switch` statement is used to perform different actions based on different conditions. Use the `switch` statement to select one of many code blocks to be executed.
```javascript
@ -96,59 +135,93 @@ switch (expression) {
// code block
break;
default:
// code block
// code block
}
```
**Understanding the structure:**
- **Evaluates** the expression once at the beginning
- **Compares** the result against each `case` value
- **Executes** the matching case block and uses `break` to exit
- **Runs** the `default` block if no cases match
```javascript
// program using switch statement
let a = 2;
// Program using switch statement for day of week
let dayNumber = 2;
let dayName;
switch (a) {
switch (dayNumber) {
case 1:
a = "one";
dayName = "Monday";
break;
case 2:
a = "two";
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
a = "not found";
dayName = "Unknown day";
break;
}
console.log(`The value is ${a}`);
console.log(`Today is ${dayName}`);
```
**Step by step, here's what's happening:**
- **Declares** a variable `dayNumber` with the value `2`
- **Evaluates** the switch expression and finds the matching `case 2`
- **Assigns** "Tuesday" to the `dayName` variable
- **Exits** the switch block using the `break` statement
- **Displays** "Today is Tuesday" in the console
✅ Test your understanding of this code and the following code by running it in a browser console. Change the values of the variable a to change the returned `console.log()`.
## Logical Operators and Booleans
Real-world decisions often involve multiple conditions. For example, you might go to the beach if it's sunny AND warm, or you might stay home if it's raining OR snowing. Logical operators allow you to combine multiple conditions in your JavaScript programs, making your decision-making logic more sophisticated and realistic.
Decisions might require more than one comparison, and can be strung together with logical operators to produce a Boolean value.
| Symbol | Description | Example |
| ------ | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `&&` | **Logical AND**: Compares two Boolean expressions. Returns true **only** if both sides are true | `(5 > 6) && (5 < 6 ) //One side is false, other is true. Returns false` |
| `\|\|` | **Logical OR**: Compares two Boolean expressions. Returns true if at least one side is true | `(5 > 6) \|\| (5 < 6) //One side is false, other is true. Returns true` |
| `!` | **Logical NOT**: Returns the opposite value of a Boolean expression | `!(5 > 6) // 5 is not greater than 6, but "!" will return true` |
| `&&` | **Logical AND**: Compares two Boolean expressions. Returns true **only** if both sides are true | `(5 > 3) && (5 < 10) // Both sides are true. Returns true` |
| `\|\|` | **Logical OR**: Compares two Boolean expressions. Returns true if at least one side is true | `(5 > 10) \|\| (5 < 10) // One side is false, other is true. Returns true` |
| `!` | **Logical NOT**: Returns the opposite value of a Boolean expression | `!(5 > 10) // 5 is not greater than 10, so "!" makes it true` |
**Understanding these operators:**
- **Combines** multiple conditions using AND (`&&`) when all must be true
- **Offers** alternatives using OR (`||`) when at least one must be true
- **Reverses** logic using NOT (`!`) to flip true/false values
## Conditions and Decisions with Logical Operators
Logical operators can be used to form conditions in if..else statements.
Now let's see how logical operators work in practice with `if..else` statements. By combining logical operators with conditional statements, you can create sophisticated decision-making logic that handles complex real-world scenarios.
Logical operators can be used to form conditions in `if..else` statements.
```javascript
let currentMoney;
let laptopPrice;
let laptopDiscountPrice = laptopPrice - laptopPrice * 0.2; //Laptop price at 20 percent off
let currentMoney = 600;
let laptopPrice = 800;
let laptopDiscountPrice = laptopPrice - (laptopPrice * 0.2); // Laptop price at 20 percent off
if (currentMoney >= laptopPrice || currentMoney >= laptopDiscountPrice) {
//Condition is true. Code in this block will run.
// Condition is true. Code in this block will run.
console.log("Getting a new laptop!");
} else {
//Condition is true. Code in this block will run.
// Condition is false. Code in this block will run.
console.log("Can't afford a new laptop, yet!");
}
```
### Negation operator
**Let's understand each part:**
- **Calculates** the discount price as 80% of original price (20% off)
- **Uses** the OR operator (`||`) to check if either condition is true
- **Evaluates** whether current money covers the full price OR the discount price
- **Executes** "Getting a new laptop!" because `600 >= 640` (discount price) is true
### Negation Operator
Sometimes it's easier to think about when something is NOT true rather than when it IS true. The negation operator (`!`) flips the logic, allowing you to write more intuitive conditions. For example, instead of checking "if user is not logged in," you can write "if not user is logged in."
You've seen so far how you can use an `if...else` statement to create conditional logic. Anything that goes into an `if` needs to evaluate to true/false. By using the `!` operator you can _negate_ the expression. It would look like so:
@ -160,14 +233,26 @@ if (!condition) {
}
```
### Ternary expressions
**Key points to remember:**
- **Flips** the Boolean value: `!true` becomes `false`, `!false` becomes `true`
- **Reads** naturally: "if not condition" makes logical sense
- **Simplifies** logic when you want to check for the absence of something
### Ternary Expressions
For simple `if...else` decisions, JavaScript offers a more concise syntax called the ternary operator. Think of it as a shorthand way to write conditional assignments it's particularly useful when you need to assign one of two values to a variable based on a condition.
`if...else` isn't the only way to express decision logic. You can also use something called a ternary operator. The syntax for it looks like this:
```javascript
let variable = condition ? <return this if true> : <return this if false>
let variable = condition ? returnThisIfTrue : returnThisIfFalse;
```
**Understanding the structure:**
- **Evaluates** the condition before the question mark `?`
- **Returns** the first value (after `?`) if condition is true
- **Returns** the second value (after `:`) if condition is false
Below is a more tangible example:
```javascript
@ -178,11 +263,10 @@ let biggestNumber = firstNumber > secondNumber ? firstNumber : secondNumber;
✅ Take a minute to read this code a few times. Do you understand how these operators are working?
The above states that
- if `firstNumber` is larger than `secondNumber`
- then assign `firstNumber` to `biggestNumber`
- else assign `secondNumber`.
The above states that:
- **Checks** if `firstNumber` is larger than `secondNumber`
- **Assigns** `firstNumber` to `biggestNumber` if the condition is true
- **Assigns** `secondNumber` to `biggestNumber` if the condition is false
The ternary expression is just a compact way of writing the code below:
@ -195,6 +279,11 @@ if (firstNumber > secondNumber) {
}
```
**What you need to know:**
- **Provides** a concise alternative to simple `if...else` statements
- **Works** best for straightforward conditional assignments
- **Improves** code readability when used appropriately for simple conditions
---

@ -1,40 +1,104 @@
# Operators
# Making Decisions: Student Grade Processor
## Instructions
## Learning Objectives
Play around with operators. Here's a suggestion for a program you can implement:
In this assignment, you'll practice the decision-making concepts from this lesson by building a program that processes student grades from different grading systems. You'll use `if...else` statements, comparison operators, and logical operators to determine which students pass their courses.
You have a set of students from two different grading systems.
## The Challenge
### First grading system
You work for a school that recently merged with another institution. Now you need to process student grades from two completely different grading systems and determine which students are passing. This is a perfect opportunity to practice conditional logic!
One grading system is defined as grades being from 1-5 where 3 and above means you pass the course.
### Understanding the Grading Systems
### Second grading system
#### First Grading System (Numeric)
- Grades are given as numbers from 1-5
- **Passing grade**: 3 and above (3, 4, or 5)
- **Failing grade**: Below 3 (1 or 2)
The other grade system has the following grades `A, A-, B, B-, C, C-` where `A` is the top grade and `C` is the lowest passing grade.
#### Second Grading System (Letter Grades)
- Grades use letters: `A`, `A-`, `B`, `B-`, `C`, `C-`
- **Passing grades**: `A`, `A-`, `B`, `B-`, `C`, `C-` (all listed grades are passing)
- **Note**: This system doesn't include failing grades like `D` or `F`
### The task
### Your Task
Given the following array `allStudents` representing all students and their grades, construct a new array `studentsWhoPass` containing all students who pass.
> TIP, use a for-loop and if...else and comparison operators:
Given the following array `allStudents` representing all students and their grades, construct a new array `studentsWhoPass` containing all students who pass according to their respective grading systems.
```javascript
let allStudents = [
'A',
'B-',
1,
4,
5,
2
]
'A', // Letter grade - passing
'B-', // Letter grade - passing
1, // Numeric grade - failing
4, // Numeric grade - passing
5, // Numeric grade - passing
2 // Numeric grade - failing
];
let studentsWhoPass = [];
```
### Step-by-Step Approach
1. **Set up a loop** to go through each grade in the `allStudents` array
2. **Check the grade type** (is it a number or a string?)
3. **Apply the appropriate grading system rules**:
- For numbers: check if grade >= 3
- For strings: check if it's one of the valid passing letter grades
4. **Add passing grades** to the `studentsWhoPass` array
### Helpful Code Techniques
Use these JavaScript concepts from the lesson:
- **typeof operator**: `typeof grade === 'number'` to check if it's a numeric grade
- **Comparison operators**: `>=` to compare numeric grades
- **Logical operators**: `||` to check multiple letter grade conditions
- **if...else statements**: to handle different grading systems
- **Array methods**: `.push()` to add passing grades to your new array
### Expected Output
When you run your program, `studentsWhoPass` should contain: `['A', 'B-', 4, 5]`
**Why these grades pass:**
- `'A'` and `'B-'` are valid letter grades (all letter grades in this system are passing)
- `4` and `5` are numeric grades >= 3
- `1` and `2` fail because they're numeric grades < 3
## Testing Your Solution
Test your code with different scenarios:
```javascript
// Test with different grade combinations
let testGrades1 = ['A-', 3, 'C', 1, 'B'];
let testGrades2 = [5, 'A', 2, 'C-', 4];
// Your solution should work with any combination of valid grades
```
## Bonus Challenges
Once you complete the basic assignment, try these extensions:
1. **Add validation**: Check for invalid grades (like negative numbers or invalid letters)
2. **Count statistics**: Calculate how many students pass vs. fail
3. **Grade conversion**: Convert all grades to a single numeric system (A=5, B=4, C=3, etc.)
## Rubric
| Criteria | Exemplary | Adequate | Needs Improvement |
| -------- | ------------------------------ | ----------------------------- | ------------------------------- |
| | Complete solution is presented | Partial solution is presented | Solution with bugs is presented |
| Criteria | Exemplary (4) | Proficient (3) | Developing (2) | Beginning (1) |
|----------|---------------|----------------|----------------|---------------|
| **Functionality** | Program correctly identifies all passing grades from both systems | Program works with minor issues or edge cases | Program partially works but has logical errors | Program has significant errors or doesn't run |
| **Code Structure** | Clean, well-organized code with proper if...else logic | Good structure with appropriate conditional statements | Acceptable structure with some organizational issues | Poor structure, difficult to follow logic |
| **Use of Concepts** | Effectively uses comparison operators, logical operators, and conditional statements | Good use of lesson concepts with minor gaps | Some use of lesson concepts but missing key elements | Limited use of lesson concepts |
| **Problem Solving** | Shows clear understanding of the problem and elegant solution approach | Good problem-solving approach with solid logic | Adequate problem-solving with some confusion | Unclear approach, doesn't demonstrate understanding |
## Submission Guidelines
1. **Test your code** thoroughly with the provided examples
2. **Add comments** explaining your logic, especially for the conditional statements
3. **Verify output** matches expected results: `['A', 'B-', 4, 5]`
4. **Consider edge cases** like empty arrays or unexpected data types
> 💡 **Pro Tip**: Start simple! Get the basic functionality working first, then add more sophisticated features. Remember, the goal is to practice decision-making logic with the tools you learned in this lesson.

@ -6,7 +6,11 @@
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/13)
This lesson covers the basics of JavaScript, the language that provides interactivity on the web. In this lesson, you'll learn about arrays and loops, which are used to manipulate data.
Arrays and loops are fundamental building blocks of programming that work together to help you organize and process data efficiently. Think of arrays as digital filing cabinets that can store multiple pieces of related information, while loops act as your tireless assistants that can perform repetitive tasks automatically. These concepts are essential for creating dynamic, interactive web applications.
In this lesson, you'll discover how to create and manipulate arrays to store collections of data, and how to use different types of loops to process that data systematically. You'll also learn how arrays and loops work together to solve real-world programming challenges, from displaying lists of items to processing user input.
By the end of this lesson, you'll be confidently working with arrays and loops to handle data manipulation tasks that would be impossible or impractical to do manually. Let's explore these powerful tools that will transform how you approach programming problems!
[![Arrays](https://img.youtube.com/vi/1U4qTyq02Xw/0.jpg)](https://youtube.com/watch?v=1U4qTyq02Xw "Arrays")
@ -18,102 +22,325 @@ This lesson covers the basics of JavaScript, the language that provides interact
## Arrays
Working with data is a common task for any language, and it's a much easier task when data is organized in a structural format, such as arrays. With arrays, data is stored in a structure similar to a list. One major benefit of arrays is that you can store different types of data in one array.
Arrays are one of the most versatile and commonly used data structures in JavaScript. They allow you to store multiple values in a single variable, making it easy to organize related information and work with collections of data. Whether you're managing a shopping list, storing user names, or handling form responses, arrays provide an elegant solution.
Let's start by understanding how to create and work with arrays in JavaScript.
✅ Arrays are all around us! Can you think of a real-life example of an array, such as a solar panel array?
The syntax for an array is a pair of square brackets.
### Creating Arrays
The syntax for an array uses square brackets to contain the elements:
```javascript
let myArray = [];
// Empty array - ready to be filled with data
const myArray = [];
```
This is an empty array, but arrays can be declared already populated with data. Multiple values in an array are separated by a comma.
**Here's what this code does:**
- **Creates** an empty array using square bracket notation `[]`
- **Uses** `const` for immutable array reference (recommended modern practice)
- **Prepares** a container ready to store multiple values
Arrays can also be created with initial data, where multiple values are separated by commas:
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
// Array with initial data
const iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
// Mixed data types in one array
const userData = ["John", 25, true, "developer"];
// Numbers array
const scores = [95, 87, 92, 78, 85];
```
The array values are assigned a unique value called the **index**, a whole number that is assigned based on its distance from the beginning of the array. In the example above, the string value "Chocolate" has an index of 0, and the index of "Rocky Road" is 4. Use the index with square brackets to retrieve, change, or insert array values.
**Understanding these examples:**
- **Groups** related string values together in the `iceCreamFlavors` array
- **Combines** different data types (string, number, boolean) in the `userData` array
- **Organizes** numerical data in the `scores` array for easy processing
### Array Indexing
Each element in an array is assigned a unique position number called an **index**. Understanding indexing is crucial for accessing and manipulating array data effectively.
| Index | Value | Description |
|-------|-------|-------------|
| 0 | "Chocolate" | First element |
| 1 | "Strawberry" | Second element |
| 2 | "Vanilla" | Third element |
| 3 | "Pistachio" | Fourth element |
| 4 | "Rocky Road" | Fifth element |
✅ Does it surprise you that arrays start at the zero index? In some programming languages, indexes start at 1. There's an interesting history around this, which you can [read on Wikipedia](https://en.wikipedia.org/wiki/Zero-based_numbering).
**Accessing Array Elements:**
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
iceCreamFlavors[2]; //"Vanilla"
const iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
// Access individual elements using bracket notation
console.log(iceCreamFlavors[0]); // "Chocolate" - first element
console.log(iceCreamFlavors[2]); // "Vanilla" - third element
console.log(iceCreamFlavors[4]); // "Rocky Road" - last element
```
You can leverage the index to change a value, like this:
**Breaking down what happens here:**
- **Uses** square bracket notation with the index number to access elements
- **Returns** the value stored at that specific position in the array
- **Starts** counting from 0, making the first element index 0
**Modifying Array Elements:**
```javascript
iceCreamFlavors[4] = "Butter Pecan"; //Changed "Rocky Road" to "Butter Pecan"
// Change an existing value
iceCreamFlavors[4] = "Butter Pecan";
console.log(iceCreamFlavors[4]); // "Butter Pecan"
// Add a new element at the end
iceCreamFlavors[5] = "Cookie Dough";
console.log(iceCreamFlavors[5]); // "Cookie Dough"
```
And you can insert a new value at a given index like this:
**In the above, we've:**
- **Modified** the element at index 4 from "Rocky Road" to "Butter Pecan"
- **Added** a new element "Cookie Dough" at index 5
- **Expanded** the array length automatically when adding beyond current bounds
### Array Length and Common Methods
Arrays come with built-in properties and methods that make working with data much easier.
**Finding Array Length:**
```javascript
iceCreamFlavors[5] = "Cookie Dough"; //Added "Cookie Dough"
const iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
console.log(iceCreamFlavors.length); // 5
// Length updates automatically as array changes
iceCreamFlavors.push("Mint Chip");
console.log(iceCreamFlavors.length); // 6
```
✅ A more common way to push values to an array is by using array operators such as array.push()
**Key points to remember:**
- **Returns** the total number of elements in the array
- **Updates** automatically when elements are added or removed
- **Provides** a dynamic count useful for loops and validation
To find out how many items are in an array, use the `length` property.
**Essential Array Methods:**
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
iceCreamFlavors.length; //5
const fruits = ["apple", "banana", "orange"];
// Add elements
fruits.push("grape"); // Adds to end: ["apple", "banana", "orange", "grape"]
fruits.unshift("strawberry"); // Adds to beginning: ["strawberry", "apple", "banana", "orange", "grape"]
// Remove elements
const lastFruit = fruits.pop(); // Removes and returns "grape"
const firstFruit = fruits.shift(); // Removes and returns "strawberry"
// Find elements
const index = fruits.indexOf("banana"); // Returns 1 (position of "banana")
const hasApple = fruits.includes("apple"); // Returns true
```
**Understanding these methods:**
- **Adds** elements with `push()` (end) and `unshift()` (beginning)
- **Removes** elements with `pop()` (end) and `shift()` (beginning)
- **Locates** elements with `indexOf()` and checks existence with `includes()`
- **Returns** useful values like removed elements or position indexes
✅ Try it yourself! Use your browser's console to create and manipulate an array of your own creation.
## Loops
Loops allow us to perform repetitive or **iterative** tasks, and can save a lot of time and code. Each iteration can vary in their variables, values, and conditions. There are different types of loops in JavaScript, and they all have small differences, but essentially do the same thing: loop over data.
Loops are powerful programming constructs that allow you to execute code repeatedly without writing the same statements multiple times. They're essential for processing arrays, generating sequences, and automating repetitive tasks. Think of loops as your programming automation tools they handle the tedious work so you can focus on solving bigger problems.
JavaScript provides several types of loops, each with specific strengths and use cases. Let's explore the most common ones and learn when to use each type.
### For Loop
The `for` loop requires 3 parts to iterate:
- `counter` A variable that is typically initialized with a number that counts the number of iterations
- `condition` Expression that uses comparison operators to cause the loop to stop when `false`
- `iteration-expression` Runs at the end of each iteration, typically used to change the counter value
The `for` loop is perfect when you know exactly how many times you want to repeat something. It's structured and predictable, making it ideal for array processing and counting operations.
**For Loop Structure:**
| Component | Purpose | Example |
|-----------|---------|----------|
| **Initialization** | Sets starting point | `let i = 0` |
| **Condition** | When to continue | `i < 10` |
| **Increment** | How to update | `i++` |
```javascript
// Counting up to 10
// Counting from 0 to 9
for (let i = 0; i < 10; i++) {
console.log(i);
console.log(`Count: ${i}`);
}
// More practical example: processing scores
const testScores = [85, 92, 78, 96, 88];
for (let i = 0; i < testScores.length; i++) {
console.log(`Student ${i + 1}: ${testScores[i]}%`);
}
```
**Step by step, here's what's happening:**
- **Initializes** the counter variable `i` to 0 at the start
- **Checks** the condition `i < 10` before each iteration
- **Executes** the code block when the condition is true
- **Increments** `i` by 1 after each iteration with `i++`
- **Stops** when the condition becomes false (when `i` reaches 10)
✅ Run this code in a browser console. What happens when you make small changes to the counter, condition, or iteration expression? Can you make it run backwards, creating a countdown?
### While loop
### While Loop
The `while` loop is ideal when you don't know exactly how many iterations you'll need, but you have a clear condition for when to stop. It's particularly useful for user input validation, searching through data, or processing until a specific state is reached.
Unlike the syntax of the `for` loop, `while` loops only require a condition that will stop the loop when the condition becomes `false`. Conditions in loops usually rely on other values like counters, and must be managed during the loop. Starting values for counters must be created outside the loop, and any expressions to meet a condition, including changing the counter must be maintained inside the loop.
**While Loop Characteristics:**
- **Continues** executing as long as the condition is true
- **Requires** manual management of any counter variables
- **Checks** the condition before each iteration
- **Risks** infinite loops if the condition never becomes false
```javascript
//Counting up to 10
// Basic counting example
let i = 0;
while (i < 10) {
console.log(i);
i++;
console.log(`While count: ${i}`);
i++; // Don't forget to increment!
}
// More practical example: processing user input
let userInput = "";
let attempts = 0;
const maxAttempts = 3;
while (userInput !== "quit" && attempts < maxAttempts) {
userInput = prompt(`Enter 'quit' to exit (attempt ${attempts + 1}):`);
attempts++;
}
if (attempts >= maxAttempts) {
console.log("Maximum attempts reached!");
}
```
**Understanding these examples:**
- **Manages** the counter variable `i` manually inside the loop body
- **Increments** the counter to prevent infinite loops
- **Demonstrates** practical use case with user input and attempt limiting
- **Includes** safety mechanisms to prevent endless execution
### Modern Loop Alternatives
JavaScript offers modern loop syntax that can make your code more readable and less error-prone.
**For...of Loop (ES6+):**
```javascript
const colors = ["red", "green", "blue", "yellow"];
// Modern approach - cleaner and safer
for (const color of colors) {
console.log(`Color: ${color}`);
}
// Compare with traditional for loop
for (let i = 0; i < colors.length; i++) {
console.log(`Color: ${colors[i]}`);
}
```
**Key advantages of for...of:**
- **Eliminates** index management and potential off-by-one errors
- **Provides** direct access to array elements
- **Improves** code readability and reduces syntax complexity
**forEach Method:**
```javascript
const prices = [9.99, 15.50, 22.75, 8.25];
// Using forEach for functional programming style
prices.forEach((price, index) => {
console.log(`Item ${index + 1}: $${price.toFixed(2)}`);
});
// forEach with arrow functions for simple operations
prices.forEach(price => console.log(`Price: $${price}`));
```
**What you need to know about forEach:**
- **Executes** a function for each array element
- **Provides** both element value and index as parameters
- **Cannot** be stopped early (unlike traditional loops)
- **Returns** undefined (doesn't create a new array)
✅ Why would you choose a for loop vs. a while loop? 17K viewers had the same question on StackOverflow, and some of the opinions [might be interesting to you](https://stackoverflow.com/questions/39969145/while-loops-vs-for-loops-in-javascript).
## Loops and Arrays
Arrays are often used with loops because most conditions require the length of the array to stop the loop, and the index can also be the counter value.
Combining arrays with loops creates powerful data processing capabilities. This pairing is fundamental to many programming tasks, from displaying lists to calculating statistics.
**Traditional Array Processing:**
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
const iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
// Classic for loop approach
for (let i = 0; i < iceCreamFlavors.length; i++) {
console.log(iceCreamFlavors[i]);
} //Ends when all flavors are printed
console.log(`Flavor ${i + 1}: ${iceCreamFlavors[i]}`);
}
// Modern for...of approach
for (const flavor of iceCreamFlavors) {
console.log(`Available flavor: ${flavor}`);
}
```
✅ Experiment with looping over an array of your own making in your browser's console.
**Let's understand each approach:**
- **Uses** array length property to determine loop boundary
- **Accesses** elements by index in traditional for loops
- **Provides** direct element access in for...of loops
- **Processes** each array element exactly once
**Practical Data Processing Example:**
```javascript
const studentGrades = [85, 92, 78, 96, 88, 73, 89];
let total = 0;
let highestGrade = studentGrades[0];
let lowestGrade = studentGrades[0];
// Process all grades with a single loop
for (let i = 0; i < studentGrades.length; i++) {
const grade = studentGrades[i];
total += grade;
if (grade > highestGrade) {
highestGrade = grade;
}
if (grade < lowestGrade) {
lowestGrade = grade;
}
}
const average = total / studentGrades.length;
console.log(`Average: ${average.toFixed(1)}`);
console.log(`Highest: ${highestGrade}`);
console.log(`Lowest: ${lowestGrade}`);
```
**Here's how this code works:**
- **Initializes** tracking variables for sum and extremes
- **Processes** each grade with a single efficient loop
- **Accumulates** the total for average calculation
- **Tracks** highest and lowest values during iteration
- **Calculates** final statistics after loop completion
✅ Experiment with looping over an array of your own making in your browser's console.
---
@ -121,13 +348,15 @@ for (let i = 0; i < iceCreamFlavors.length; i++) {
Use the Agent mode to complete the following challenge:
**Description:** Build a data processing function that combines arrays and loops to analyze a dataset.
**Description:** Build a comprehensive data processing function that combines arrays and loops to analyze a dataset and generate meaningful insights.
**Prompt:** Create a function called `analyzeGrades` that takes an array of student grade objects (each containing name and score properties) and returns statistics including the highest score, lowest score, average score, and count of students who passed (score >= 70). Use loops to process the data.
**Prompt:** Create a function called `analyzeGrades` that takes an array of student grade objects (each containing name and score properties) and returns an object with statistics including the highest score, lowest score, average score, count of students who passed (score >= 70), and an array of student names who scored above average. Use at least two different loop types in your solution.
## 🚀 Challenge
There are other ways of looping over arrays other than for and while loops. There are [forEach](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach), [for-of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [map](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map). Rewrite your array loop using one of these techniques.
JavaScript offers several modern array methods that can replace traditional loops for specific tasks. Explore [forEach](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach), [for-of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), [map](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map), [filter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), and [reduce](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).
**Your challenge:** Rewrite the student grades analysis using at least three different modern array methods. Compare the readability and efficiency of your solutions.
## Post-Lecture Quiz
[Post-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/14)

@ -1,13 +1,108 @@
# Loop an Array
# Arrays and Loops Assignment
## Instructions
Complete the following exercises to practice working with arrays and loops. Each exercise builds on concepts from the lesson and encourages you to apply different loop types and array methods.
### Exercise 1: Number Pattern Generator
Create a program that lists every 3rd number between 1-20 and prints it to the console.
> TIP: use a for-loop and modify the iteration-expression
**Requirements:**
- Use a `for` loop with a custom increment
- Display numbers in a user-friendly format
- Add descriptive comments explaining your logic
**Expected Output:**
```
3, 6, 9, 12, 15, 18
```
> **Tip:** Modify the iteration-expression in your for loop to skip numbers.
### Exercise 2: Array Analysis
Create an array of at least 8 different numbers and write functions to analyze the data.
**Requirements:**
- Create an array called `numbers` with at least 8 values
- Write a function `findMaximum()` that returns the highest number
- Write a function `findMinimum()` that returns the lowest number
- Write a function `calculateSum()` that returns the total of all numbers
- Test each function and display the results
**Bonus Challenge:** Create a function that finds the second highest number in the array.
### Exercise 3: String Array Processing
Create an array of your favorite movies/books/songs and practice different loop types.
**Requirements:**
- Create an array with at least 5 string values
- Use a traditional `for` loop to display items with numbers (1. Item Name)
- Use a `for...of` loop to display items in uppercase
- Use `forEach()` method to count and display the total characters
**Example Output:**
```
Traditional for loop:
1. The Matrix
2. Inception
3. Interstellar
For...of loop (uppercase):
THE MATRIX
INCEPTION
INTERSTELLAR
Character count:
Total characters across all titles: 42
```
### Exercise 4: Data Filtering (Advanced)
Create a program that processes an array of objects representing students.
**Requirements:**
- Create an array of at least 5 student objects with properties: `name`, `age`, `grade`
- Use loops to find students who are 18 or older
- Calculate the average grade of all students
- Create a new array containing only students with grades above 85
**Example Structure:**
```javascript
const students = [
{ name: "Alice", age: 17, grade: 92 },
{ name: "Bob", age: 18, grade: 84 },
// Add more students...
];
```
## Testing Your Code
Test your programs by:
1. Running each exercise in your browser's console
2. Verifying outputs match expected results
3. Testing with different data sets
4. Checking that your code handles edge cases (empty arrays, single elements)
## Submission Guidelines
Include the following in your submission:
- Well-commented JavaScript code for each exercise
- Screenshots or text output showing your programs running
- Brief explanation of which loop type you chose for each task and why
## Rubric
| Criteria | Exemplary | Adequate | Needs Improvement |
| -------- | --------------------------------------- | ------------------------ | ------------------------------ |
| | Program runs correctly and is commented | Program is not commented | Program is incomplete or buggy |
| Criteria | Exemplary (3 points) | Adequate (2 points) | Needs Improvement (1 point) |
| -------- | -------------------- | ------------------- | --------------------------- |
| **Functionality** | All exercises completed correctly with bonus challenges | All required exercises work correctly | Some exercises incomplete or contain errors |
| **Code Quality** | Clean, well-organized code with descriptive variable names | Code works but could be cleaner | Code is messy or hard to understand |
| **Comments** | Comprehensive comments explaining logic and decisions | Basic comments present | Minimal or no comments |
| **Loop Usage** | Demonstrates understanding of different loop types appropriately | Uses loops correctly but limited variety | Incorrect or inefficient loop usage |
| **Testing** | Evidence of thorough testing with multiple scenarios | Basic testing demonstrated | Little evidence of testing |
## Reflection Questions
After completing the exercises, consider:
1. Which type of loop felt most natural to use and why?
2. What challenges did you encounter when working with arrays?
3. How could these skills apply to real-world web development projects?
4. What would you do differently if you had to optimize your code for performance?
Loading…
Cancel
Save