JavaScript for React

Essential Foundations for Modern Web Development (AI-Assisted Learning)

javascript
react preparation
async programming
AI-Assisted Development
Lecture
Auteur
Affiliations

Université de Toulon

LIS UMR CNRS 7020

Date de publication

2025-10-12

Résumé

Course lectures and practices for JavaScript full‑stack web development with AI‑assisted workflows.

🎯 Today’s Mission

Our Goal: Get You Ready for React

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!

Remember from Session 1: The AI-First Approach

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 and let correctly (never var)
  • ✅ 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 = counter + 1; // OK

// 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;
count = 1; // ERROR!

AI often generates var - this is your first verification!

🤖 AI Demo: Variables

Let’s Generate Some Code!

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 + (price * tax);

// 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 => 
  price * 1.2
);

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 => p.price > 50
);

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

Challenge: Generate & Verify

Use AI to create:

  1. An array of 3 products (name, price, category)
  2. A function that filters products by minimum price
  3. 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

  1. const by default, let when needed - Never var!
  2. Arrow functions for callbacks - Traditional for main functions
  3. Template literals for strings - Use backticks `${}`
  4. Objects with dot notation - Like PHP but . not ->
  5. map transforms, filter selects - React will use these constantly
  6. 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

The Pattern You’ll Use Everywhere
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:

  1. async keyword on function
  2. await keyword before promises
  3. try/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

Let’s Fetch Real 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

Challenge: Fetch Real Data

Use AI to create a function that:

  1. Fetches posts from https://jsonplaceholder.typicode.com/posts
  2. Filters posts by userId = 1
  3. Returns only the titles
  4. 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

  1. Async = non-blocking - Other code runs while waiting
  2. async/await pattern - Makes async look synchronous
  3. fetch(url) - Gets data from APIs
  4. await response.json() - Parses JSON response
  5. try/catch - Handles errors
  6. Check response.ok - Verify success before parsing
  7. 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

Optional Content - Read Later

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

Modern Element Selection
// 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!)
title.textContent = "New Title";

// Even with user input (safe!)
const userInput = "<script>alert('hack')</script>";
title.textContent = userInput;
// Shows literal text, not code

⚠️ Dangerous: innerHTML

const container = document
  .querySelector('#container');

// Read HTML
console.log(container.innerHTML);
// "<p>Hello</p>"

// Update HTML (dangerous!)
container.innerHTML = "<p>New</p>";

// User input (DANGEROUS!)
const userInput = "<script>alert('hack')</script>";
container.innerHTML = userInput;
// 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
button.addEventListener('click', () => {
  console.log('Button clicked!');
});

// With async function
button.addEventListener('click', async () => {
  const data = await fetch('https://api.example.com/data');
  const json = await data.json();
  console.log(json);
});

// Form submit
const form = document.querySelector('#myForm');
form.addEventListener('submit', (event) => {
  event.preventDefault(); // Stop form from reloading page!
  console.log('Form submitted');
});

Pattern: querySelector + addEventListener = Interactive page

🤖 AI Demo: Button + Fetch

Let’s Make a Button Work!

Prompt to AI:

Create JavaScript code that:
1. Selects a button with id "loadBtn"
2. Adds a click event listener
3. When clicked, fetches a random user from 
   https://jsonplaceholder.typicode.com/users/1
4. Displays the user's name in an element with id "output"
5. Uses async/await and textContent

HTML Setup (try in CodePen):

<button id="loadBtn">Load User</button>
<div id="output"></div>

Everyone try this - see vanilla JS in action!

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
button.addEventListener('click', async () => {
  
  // 3. Fetch data
  const response = await fetch('https://api.example.com/products');
  const products = await response.json();
  
  // 4. Update DOM manually (tedious!)
  output.textContent = ''; // Clear first
  products.forEach(product => {
    const div = document.createElement('div');
    div.textContent = `${product.name} - $${product.price}`;
    output.appendChild(div);
  });
});

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');
div.textContent = product.name;
div.addEventListener('click', handler);
document.body.appendChild(div);

// React: 1 line
<div onClick={handler}>{product.name}</div>

You’ll learn the React way next week

Key Takeaways: DOM Basics

  1. DOM = JavaScript’s view of HTML - You can change it
  2. querySelector - The only selector you need
  3. textContent - Safe way to update content
  4. addEventListener - Make things interactive
  5. event.preventDefault() - Stop default behavior (forms)
  6. This is tedious! - React makes it 10x easier

Why React is Better

Vanilla JS Problems

// Manual DOM updates
productsDiv.innerHTML = '';
products.forEach(product => {
  const div = document
    .createElement('div');
  div.textContent = product.name;
  productsDiv.appendChild(div);
});

// 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

React’s Superpowers 🦸‍♀️
  1. Components - Reusable UI pieces

    <ProductCard product={p} onAddToCart={handleAdd} />
  2. State Management - Automatic UI updates

    const [products, setProducts] = useState([]);
    setProducts(newProducts); // UI updates automatically!
  3. Declarative - Describe what you want, not how

    {products.map(p => <div>{p.name}</div>)}
  4. Virtual DOM - React optimizes updates for you

  5. Ecosystem - React Router, Redux, thousands of libraries

Key Takeaways: Session 2

  1. JavaScript basics - const/let, functions, objects, arrays
  2. Async/await - Pattern for fetching data
  3. fetch() API - Get data from servers
  4. DOM basics - querySelector, addEventListener, textContent
  5. Vanilla JS is tedious - Manual DOM manipulation is hard
  6. React solves these problems - You’re motivated now!
  7. AI is your friend - Use CRISP prompts to generate code
  8. You verify, not memorize - Understand patterns, AI knows details

🎯 Are You Ready for React?

Self-Check ✅

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

FAQ

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.

Réutilisation