JavaScript for React
Essential Foundations for Modern Web Development (AI-Assisted Learning)
Course lectures and practices for JavaScript full‑stack web development with AI‑assisted workflows.
🎯 Today’s Mission
Not: Make you JavaScript experts
But: Give you just enough to start building with AI assistance
Philosophy: Learn what you need NOW. Deep dives come later when you’re actually using them.
Translation: We’re teaching you to drive, not to build a car! 🚗
📋 Your 90-Minute Journey
Part 1: JavaScript Essentials
- Variables & functions
- Objects & arrays
- Template literals
- Just enough to generate code
Part 2: Async Basics
- Why async matters
- async/await pattern
- Fetch API basics
- Just enough for React data
Part 3: React Motivation
- Why vanilla JS gets painful
- React preview
- Next session preparation
Optional Reading:
- Advanced DOM manipulation
- localStorage patterns
- Complex async patterns
- See (webdev_02_L_02C_JavaScriptAdvanced)[webdev_02_L_02C_JavaScriptAdvanced.html]
🤖 Session 2 = Still AI-First!
You are the senior developer 🎯
AI is your junior assistant 🤖
- AI generates code
- You verify it’s correct
- You understand the patterns
- You fix AI’s mistakes
Today: Every code example generated with AI. You’ll learn to verify, not memorize!
💡 For PHP Developers: Quick Context
Concept | PHP | JavaScript |
---|---|---|
Variables | $name = "Alice"; |
const name = "Alice"; |
Arrays | [1, 2, 3] |
[1, 2, 3] (same!) |
Functions | function greet($n) {...} |
function greet(n) {...} |
Control | if , for , while |
Same syntax! |
Key differences to watch:
- ❌ No
$
prefix - ❌ No
->
operator (use.
) - 🆕 Async programming (new paradigm)
Good news: 70% of your backend knowledge transfers! Focus on the 30% that’s different.
Part 1: JavaScript Essentials
Learning Objectives (Part 1)
By the end of this section, you’ll be able to:
- ✅ Use
const
andlet
correctly (nevervar
) - ✅ Write arrow functions (modern syntax)
- ✅ Work with objects and arrays
- ✅ Use template literals for strings
- ✅ Generate all of this with AI and verify it works
Remember: You don’t need to memorize syntax. You need to recognize correct patterns!
Variables: const vs let
✅ Modern JavaScript
// Use const for values that don't change
const name = "Alice";
const age = 25;
const user = {name: "Bob"};
// Use let only when reassigning
let counter = 0;
= counter + 1; // OK
counter
// Never use var (outdated!)
Rule: Default to const
, use let
only when needed
❌ Common Mistakes
// ❌ Using var (old, confusing)
var name = "Alice";
// ❌ Using let when const works
let PI = 3.14; // Never changes!
// ❌ Trying to reassign const
const count = 0;
= 1; // ERROR! count
AI often generates var - this is your first verification!
🤖 AI Demo: Variables
Prompt to AI:
Create a JavaScript object representing a product with
name, price, and inStock properties. Use const.
Expected AI Output:
const product = {
name: "Laptop",
price: 999,
inStock: true
; }
Your Verification:
- ✅ Uses
const
? (Good!) - ✅ Object syntax correct? (Looks good!)
- ✅ Makes sense? (Yes!)
Everyone try this now in your console! (F12 → Console)
Functions: Traditional vs Arrow
Traditional Function
function greet(name) {
return "Hello " + name;
}
function calculateTotal(price, tax) {
return price + (price * tax);
}
// Good for: Main functions, methods
Arrow Function (Modern)
const greet = (name) => {
return `Hello ${name}`;
;
}
// Or shorter (implicit return):
const greet = name => `Hello ${name}`;
const calculateTotal = (price, tax) =>
+ (price * tax);
price
// Good for: Callbacks, map/filter
When to use which? Arrow functions for short operations, traditional for complex logic.
Template Literals: Better Strings
❌ Old Way (Don’t Use)
const name = "Alice";
const age = 25;
// String concatenation (ugly!)
const message = "Hello " + name +
", you are " + age + " years old";
console.log(message);
Problems:
- Hard to read
- Easy to forget spaces
- Can’t span lines easily
✅ Modern Way (Use This!)
const name = "Alice";
const age = 25;
// Template literals (beautiful!)
const message = `Hello ${name},
you are ${age} years old`;
console.log(message);
Benefits:
- Easy to read
- Expressions inside
${}
- Multi-line strings
- React JSX uses similar syntax!
Objects & Arrays: The Basics
// Object: Key-value pairs (like PHP associative arrays)
const user = {
name: "Alice",
age: 25,
email: "alice@example.com"
;
}
// Access with dot notation
console.log(user.name); // "Alice"
console.log(user.age); // 25
// Arrays: Ordered lists
const products = [
name: "Laptop", price: 999},
{name: "Mouse", price: 25},
{name: "Keyboard", price: 75}
{;
]
// Access by index
console.log(products[0].name); // "Laptop"
console.log(products.length); // 3
For PHP developers: Objects = associative arrays, but use .
not [
]
Array Methods: map & filter
map: Transform Each Item
const prices = [10, 20, 30];
// Add tax to each price
const withTax = prices.map(price =>
* 1.2
price ;
)
console.log(withTax);
// [12, 24, 36]
Use when: You need to transform every item
filter: Select Items
const products = [
name: "Laptop", price: 999},
{name: "Mouse", price: 25},
{name: "Keyboard", price: 75}
{;
]
// Only expensive items
const expensive = products.filter(
=> p.price > 50
p ;
)
console.log(expensive);
// [{name: "Laptop", ...},
// {name: "Keyboard", ...}]
Use when: You need to select some items
React uses these CONSTANTLY! Get comfortable with the pattern.
🎯 Practice: JavaScript Essentials
Use AI to create:
- An array of 3 products (name, price, category)
- A function that filters products by minimum price
- A function that adds 20% tax to all prices
Your CRISP Prompt:
Create a JavaScript array of 3 products with name, price,
and category. Then create two functions:
1. filterByPrice(products, minPrice) - returns products >= minPrice
2. addTax(products, taxRate) - returns products with tax added to price
Use modern JavaScript (const, arrow functions, map/filter).
Verify:
- ✅ Uses const/let (no var)
- ✅ Arrow functions for callbacks
- ✅ map/filter used correctly
Key Takeaways: JavaScript Essentials
- const by default, let when needed - Never var!
- Arrow functions for callbacks - Traditional for main functions
- Template literals for strings - Use backticks `${}`
- Objects with dot notation - Like PHP but
.
not->
- map transforms, filter selects - React will use these constantly
- AI generates, you verify - Check for modern syntax!
Are you ready for async? Let’s learn to fetch data! 🚀
Part 2: Async Basics
Why Async? The Restaurant Analogy 🍽️
❌ Synchronous (PHP-style)
1. Take order from table 1
→ WAIT for kitchen →
2. Deliver food to table 1
→ WAIT for them to finish →
3. Take order from table 2
→ WAIT for kitchen →
4. Deliver food to table 2
Problem: One customer at a time!
Restaurant: Empty while waiting
Code: Frozen UI while fetching data
✅ Asynchronous (JavaScript)
1. Take order table 1 → kitchen
2. Take order table 2 → kitchen
3. Take order table 3 → kitchen
(while kitchen cooks)
4. Deliver food as ready
5. Keep taking new orders
Benefit: Serve many customers!
Restaurant: Always busy
Code: Responsive UI while loading
Async/Await: Making Async Look Sync
async function fetchData() {
try {
// 1. Mark function as async
// 2. Use await to pause until promise resolves
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
return data;
catch (error) {
} // 3. Handle errors
console.error('Something went wrong:', error);
} }
Three parts:
async
keyword on functionawait
keyword before promisestry/catch
for errors
This is ALL you need to know about async for now!
Fetch API: Getting Data from Servers
The Pattern
async function getUsers() {
try {
const response = await fetch(
'https://api.example.com/users'
;
)
const users = await response.json();
console.log(users);
return users;
catch (error) {
} console.error('Error:', error);
} }
Common Mistakes
// ❌ Forgot async
function getUsers() {
await fetch(url); // ERROR!
}
// ❌ Forgot await
async function getUsers() {
const response = fetch(url);
// response is Promise, not data!
}
// ❌ Forgot .json()
async function getUsers() {
const response = await fetch(url);
console.log(response);
// Just response object, not data!
}
🤖 AI Demo: Fetch Data
Prompt to AI:
Create an async function that fetches users from
https://jsonplaceholder.typicode.com/users
and returns only their names as an array.
Use async/await and proper error handling.
Expected Pattern:
async function getUserNames() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await response.json();
const names = users.map(user => user.name);
return names;
catch (error) {
} console.error('Error fetching users:', error);
return [];
} }
Everyone test this in your console now!
Error Handling: The Right Way
async function fetchProducts() {
try {
const response = await fetch('https://api.example.com/products');
// Check if request was successful
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const products = await response.json();
return products;
catch (error) {
} console.error('Failed to fetch products:', error);
// Return empty array or default value
return [];
} }
Pro tip: Always check response.ok
before parsing JSON!
🎯 Practice: Async & Fetch
Use AI to create a function that:
- Fetches posts from
https://jsonplaceholder.typicode.com/posts
- Filters posts by userId = 1
- Returns only the titles
- Includes error handling
Your CRISP Prompt:
Create an async function fetchUserPosts(userId) that:
- Fetches posts from https://jsonplaceholder.typicode.com/posts
- Filters for posts matching the userId parameter
- Returns an array of just the post titles
- Includes try/catch error handling
- Checks response.ok before parsing JSON
Test it: fetchUserPosts(1)
should return array of titles
What We’re NOT Teaching (Yet)
❌ Skipping For Now
- Callbacks (outdated pattern)
- Promise
.then()
syntax (confusing) - Promise constructor
Promise.all()
,Promise.race()
- POST/PUT/DELETE requests
- Request headers & authentication
- Advanced error handling patterns
✅ Why Skip?
You don’t need them yet!
- React data fetching: Just GET with fetch
- Advanced patterns: Learn in Express session
- Headers/auth: Learn when building APIs
- Promise.all: Learn when needed
Philosophy: Just-in-time learning
Next session (Express): We’ll cover POST, headers, authentication, parallel requests, etc.
Key Takeaways: Async Basics
- Async = non-blocking - Other code runs while waiting
- async/await pattern - Makes async look synchronous
- fetch(url) - Gets data from APIs
- await response.json() - Parses JSON response
- try/catch - Handles errors
- Check response.ok - Verify success before parsing
- This is enough for React! - Deep dive in Express session
Ready for React motivation? Let’s see why we need it! 🎨
Part 3: Why React? (React Motivation)
15 Minutes: From Vanilla JS Pain to React Joy
The Vanilla JavaScript Challenge
Session 2 Summary: You now know enough JavaScript to:
- ✅ Create variables and functions
- ✅ Work with objects and arrays
- ✅ Fetch data from APIs with async/await
- ✅ Generate code with AI assistance
But: Building complex UIs with vanilla JavaScript becomes painful…
📚 Optional Reading: Advanced DOM & Patterns
The following content contains valuable DOM manipulation concepts, but they’re optional for this session due to time constraints.
When to read: After Session 3 (React), when you want to understand what React does behind the scenes.
File reference: See webdev_02_L_02C_JavaScriptAdvanced.qmd
for more advanced patterns.
Part 3: DOM Intro
Original 30-Minute Content (Now Optional)
HTML (What You Write)
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1 id="title">Hello</h1>
<button id="btn">Click</button>
</body>
</html>
DOM (Browser’s View)
// Browser creates JavaScript objects
document = {
head: { /* ... */ },
body: {
children: [
type: "h1", id: "title", ...},
{type: "button", id: "btn", ...}
{
]
}
}
// You can manipulate these objects!
DOM = JavaScript’s way to access and modify HTML
querySelector: The Only Selector You Need
// Select by ID
const title = document.querySelector('#title');
// Select by class
const button = document.querySelector('.btn-primary');
// Select by tag
const firstDiv = document.querySelector('div');
// Complex selectors (like CSS!)
const item = document.querySelector('ul > li:first-child');
const button = document.querySelector('button.active[data-id="5"]');
Why just querySelector? - Works for everything (ID, class, tag, complex) - Same syntax as CSS selectors - Modern and flexible
Old methods (getElementById, getElementsByClassName) - forget them!
Updating Content: textContent
✅ Safe Way: textContent
const title = document
.querySelector('#title');
// Read content
console.log(title.textContent);
// "Hello"
// Update content (safe!)
.textContent = "New Title";
title
// Even with user input (safe!)
const userInput = "<script>alert('hack')</script>";
.textContent = userInput;
title// Shows literal text, not code
⚠️ Dangerous: innerHTML
const container = document
.querySelector('#container');
// Read HTML
console.log(container.innerHTML);
// "<p>Hello</p>"
// Update HTML (dangerous!)
.innerHTML = "<p>New</p>";
container
// User input (DANGEROUS!)
const userInput = "<script>alert('hack')</script>";
.innerHTML = userInput;
container// Executes the script! ⚠️
Only use innerHTML with trusted content!
Event Listeners: Making Things Interactive
// 1. Select the element
const button = document.querySelector('#loadButton');
// 2. Add event listener
.addEventListener('click', () => {
buttonconsole.log('Button clicked!');
;
})
// With async function
.addEventListener('click', async () => {
buttonconst data = await fetch('https://api.example.com/data');
const json = await data.json();
console.log(json);
;
})
// Form submit
const form = document.querySelector('#myForm');
.addEventListener('submit', (event) => {
formevent.preventDefault(); // Stop form from reloading page!
console.log('Form submitted');
; })
Pattern: querySelector
+ addEventListener
= Interactive page
The Vanilla JS Pattern
// This is what you'll do in vanilla JavaScript:
// 1. Select elements
const button = document.querySelector('#loadBtn');
const output = document.querySelector('#output');
// 2. Add event listener
.addEventListener('click', async () => {
button
// 3. Fetch data
const response = await fetch('https://api.example.com/products');
const products = await response.json();
// 4. Update DOM manually (tedious!)
.textContent = ''; // Clear first
output.forEach(product => {
productsconst div = document.createElement('div');
.textContent = `${product.name} - $${product.price}`;
div.appendChild(div);
output;
}); })
Notice: Manual DOM manipulation is tedious! Imagine 100 products, multiple updates…
What We’re NOT Teaching About DOM
❌ Skipping (React Does This)
- DOM tree navigation (parent, child, sibling)
getElementById
,getElementsByClassName
createElement
,appendChild
patterns- Event delegation
- Event propagation (capture/bubble)
- Form handling details
innerHTML
(dangerous anyway)- localStorage (later project)
- Performance optimization
✅ Why Skip?
React replaces ALL of this!
// Vanilla JS: 20 lines
const div = document.createElement('div');
.textContent = product.name;
div.addEventListener('click', handler);
divdocument.body.appendChild(div);
// React: 1 line
<div onClick={handler}>{product.name}</div>
You’ll learn the React way next week
Key Takeaways: DOM Basics
- DOM = JavaScript’s view of HTML - You can change it
- querySelector - The only selector you need
- textContent - Safe way to update content
- addEventListener - Make things interactive
- event.preventDefault() - Stop default behavior (forms)
- This is tedious! - React makes it 10x easier
Why React is Better
Vanilla JS Problems
// Manual DOM updates
.innerHTML = '';
productsDiv.forEach(product => {
productsconst div = document
.createElement('div');
.textContent = product.name;
div.appendChild(div);
productsDiv;
})
// Managing state manually
let isLoading = false;
let products = [];
let error = null;
// No automatic re-rendering
// You update DOM yourself!
React Solutions
// Declarative rendering
return products.map(product => (
<div>{product.name}</div>
;
))
// State management built-in
const [products, setProducts]
= useState([]);
// Automatic re-rendering
setProducts(newProducts);
// React updates DOM automatically!
// Component reusability
<ProductCard product={p} onAddToCart={handleAdd} />
Imagine Adding More Features…
Vanilla JS gets exponentially harder: - ❌ Add filter by price? Manual DOM rebuild - ❌ Add sorting? More DOM manipulation - ❌ Add shopping cart? Track state everywhere - ❌ Add product details? More event listeners - ❌ Update individual items? Find element, update manually - ❌ Add animations? Complex DOM manipulation
React stays manageable: - ✅ Filter: products.filter(...)
in render - ✅ Sort: products.sort(...)
in render - ✅ Cart: const [cart, setCart] = useState([])
- ✅ Details: <ProductDetails product={selected} />
- ✅ Update: setProducts(...)
- React handles DOM! - ✅ Animations: Built-in transition tools
What React Gives You
Components - Reusable UI pieces
<ProductCard product={p} onAddToCart={handleAdd} />
State Management - Automatic UI updates
const [products, setProducts] = useState([]); setProducts(newProducts); // UI updates automatically!
Declarative - Describe what you want, not how
.map(p => <div>{p.name}</div>)} {products
Virtual DOM - React optimizes updates for you
Ecosystem - React Router, Redux, thousands of libraries
Key Takeaways: Session 2
- JavaScript basics - const/let, functions, objects, arrays
- Async/await - Pattern for fetching data
- fetch() API - Get data from servers
- DOM basics - querySelector, addEventListener, textContent
- Vanilla JS is tedious - Manual DOM manipulation is hard
- React solves these problems - You’re motivated now!
- AI is your friend - Use CRISP prompts to generate code
- You verify, not memorize - Understand patterns, AI knows details
🎯 Are You Ready for React?
Can you:
If you checked 6+ boxes: You’re ready! 🚀
If you checked fewer: Review the reference docs, practice more
Session 2 Resources
Common Questions
Q: “Do I need to memorize all this JavaScript?”
A: No! Use AI to generate, you verify. Focus on patterns.
Q: “Why not teach promises and callbacks?”
A: async/await is simpler and modern. Learn others when needed.
Q: “Why so little DOM?”
A: React replaces it all! Just need to understand what React automates.
Q: “What if I want to deep dive?”
A: Read the reference docs! Everything’s there for curious students.
Q: “Is vanilla JS ever useful?”
A: Yes! Small scripts, browser extensions, understanding React better.
Q: What about TypeScript?
A: TypeScript is great! But adds complexity. Learn JavaScript first.