Class 17 - JavaScript Introduction

JavaScript Foundations

Variables and Operators

CSCI 3403 - Web Programming

Week 9, Class 17

Time to make our websites interactive! 🚀

Today's Learning Objectives 🎯

Our Web Development Journey 🗺️

✅ HTML

Structure & Content

We built the skeleton

✅ CSS

Style & Design

We made it beautiful

⚡ JavaScript

Behavior & Logic

Today: Make it interactive!

Remember: JavaScript is the only actual programming language of the three!

What Can JavaScript Do?

Interactive Features

  • Respond to clicks
  • Validate forms
  • Create animations
  • Update content dynamically

Examples You Use Daily

  • Like buttons
  • Image carousels
  • Shopping carts
  • Real-time updates
JavaScript brings your webpage to life! 🎭

How to Run JavaScript Code 🏃‍♂️

Method 1: Inside HTML with <script> tags

<!DOCTYPE html> <html> <head> <title>My First JS</title> </head> <body> <script> // Your JavaScript goes here! console.log("Hello, World!"); </script> </body> </html>
VS Code Tip: Type ! + TAB to create HTML boilerplate instantly!

The Browser Console 🔍

Your JavaScript Command Center

Let's Open It Together!

  1. Right-click on any webpage
  2. Click "Inspect" or "Inspect Element"
  3. Find and click the "Console" tab
  4. You should see our "Hello, World!" message!
Hello, World!
Shortcut: Press F12 or Cmd+Option+J (Mac) / Ctrl+Shift+J (Windows)

Method 2: External JavaScript Files 📁

HTML File (index.html)

<!DOCTYPE html> <html> <body> <script src="script.js"></script> </body> </html>

JavaScript File (script.js)

// script.js console.log("Hello from external file!"); // All your JavaScript code // goes in this .js file
Important: The .js extension is required!

VS Code Live Preview 🔄

No More Manual Refreshing!

The Live Preview extension automatically updates your browser when you save.

Quick Setup:

  1. Install "Live Preview" extension in VS Code
  2. Right-click your HTML file
  3. Select "Show Preview"
  4. Edit and save - watch it update instantly!
Let's try it together with our Hello World example!

Variables: Storage Containers 📦

Think of variables as labeled boxes for your data

name = "John"
age = 25
isStudent = true
// Declaring variables with let let name = "John"; let age = 25; let isStudent = true; console.log(name); // Output: John console.log(age); // Output: 25 console.log(isStudent); // Output: true

Two Ways to Declare Variables 🔄

let

Can be changed (reassigned)

let age = 25; age = 26; // ✅ This works! console.log(age); // 26

const

Cannot be changed (constant)

const pi = 3.14; pi = 3; // ❌ ERROR! // TypeError: Assignment to constant variable
Best Practice: Use const by default, only use let when you need to reassign

Reassigning Variables ♻️

let score = 0; console.log(score); // Output: 0 score = 10; // Note: no 'let' needed here! console.log(score); // Output: 10 score = score + 5; console.log(score); // Output: 15
Common Mistake: Don't use let when reassigning!
let name = "Alice"; let name = "Bob"; // ❌ ERROR: name already declared name = "Bob"; // ✅ Correct way

The Old Way: var 👴

// The original way (pre-2015) var oldSchool = "I'm old!"; // Modern JavaScript (ES6+) let modern = "I'm new!"; const newest = "I'm the newest!";

❌ var

  • Has confusing scoping rules
  • Can cause unexpected bugs
  • Outdated - avoid using!

✅ let & const

  • Clear, predictable behavior
  • Modern best practices
  • Use these instead!

Numbers in JavaScript 🔢

Basic Math Operations

+
Addition
5 + 3 = 8
-
Subtraction
10 - 4 = 6
*
Multiplication
3 * 7 = 21
/
Division
20 / 4 = 5
%
Remainder
10 % 3 = 1
**
Exponent
2 ** 3 = 8
console.log(23 + 97); // 120 console.log((4 + 6 + 9) / 77); // 0.24675...

Order of Operations (PEMDAS) 📐

JavaScript follows mathematical rules!

// Parentheses first, then multiplication, then addition console.log(2 + 3 * 4); // 14 (not 20!) console.log((2 + 3) * 4); // 20 // Complex expression console.log((3 + 2) - 76 * (1 + 1)); // 5 - 152 = -147

PEMDAS Reminder:

  1. Parentheses
  2. Exponents (**)
  3. Multiplication (*) & Division (/)
  4. Addition (+) & Subtraction (-)

Using Variables with Math 🧮

// Store numbers in variables let apples = 5; let oranges = 3; let totalFruit = apples + oranges; console.log(totalFruit); // 8 // Update variables with calculations let score = 100; score = score + 50; // Add 50 to current score console.log(score); // 150 // Using const for calculations const taxRate = 0.08; const price = 100; const total = price + (price * taxRate); console.log(total); // 108

Increment & Decrement ➕➖

Long Way

let count = 0; count = count + 1; // Add 1 count = count - 1; // Subtract 1

Shortcut Way

let count = 0; count++; // Add 1 count--; // Subtract 1
// Other shortcuts let score = 10; score += 5; // Same as: score = score + 5 score -= 3; // Same as: score = score - 3 score *= 2; // Same as: score = score * 2 score /= 4; // Same as: score = score / 4

Let's Practice! 💻

Hands-On Exercises

We'll work through these together:

  1. Add 2 numbers and log the result
  2. Add 6 different numbers
  3. Calculate expressions with parentheses
  4. Create and reassign variables
  5. Work with constants
  6. Build a percentage calculator
Setup: Create a new HTML file with a <script> tag, or use an external .js file

Exercise 1: Basic Addition

Task 1: Add Two Numbers

In your script tag, type:

console.log(23 + 97);

Expected output:

120

Task 2: Add Six Numbers

Try this:

console.log(10 + 20 + 30 + 5 + 15 + 20);

What do you get?

Exercise 2: Complex Expressions 🧮

Task 3: Division with Parentheses

console.log((4 + 6 + 9) / 77);
0.24675324675324675

Let's trace through it:

  1. (4 + 6 + 9) = 19
  2. 19 / 77 = 0.24675...
What happens if you remove the parentheses? Try it!

Exercise 3: Working with Variables 📦

Follow Along:

// Step 1: Declare a variable let a = 10; console.log(a); // Should log: 10 // Step 2: Reassign it a = 25; console.log(a); // Should log: 25 // Step 3: Use it in math let b = 7 * a; console.log(b); // Should log: ?
What is the value of b? Calculate it mentally first, then run the code!

Exercise 4: Percentage Calculator 📊

Build a Grade Calculator:

// Declare constants const max = 57; const actual = max - 13; const percentage = actual / max; console.log("Maximum points: " + max); console.log("Actual points: " + actual); console.log("Percentage: " + percentage);

Expected Output:

Maximum points: 57
Actual points: 44
Percentage: 0.7719298245614035

Common Beginner Mistakes ⚠️

❌ Wrong

let name = "Alice"; let name = "Bob"; // ERROR! const pi = 3.14; pi = 3.14159; // ERROR! console.log(Score); // ERROR! // (variable names are case-sensitive)

✅ Correct

let name = "Alice"; name = "Bob"; // Good! let pi = 3.14; pi = 3.14159; // Good! console.log(score); // Good! // (consistent case)

Quick Preview: Strings 📝

We can also work with text (strings)!

let firstName = "John"; let lastName = "Doe"; let fullName = firstName + " " + lastName; console.log(fullName); // "John Doe" // Combining strings and numbers let age = 25; let message = "I am " + age + " years old"; console.log(message); // "I am 25 years old"
We'll explore strings in detail next class!

Homework Assignment 📚

Complete the Practice Exercises

Finish all the exercises from today's lesson:

  1. Complete any unfinished in-class exercises
  2. Experiment with different number combinations
  3. Try creating your own calculator for something useful:
    • Tip calculator
    • Age in days/hours/minutes
    • Pizza slice calculator

Reading Assignment:

  • JavaScript.info - Variables
  • MDN - JavaScript Math
  • W3Schools - JavaScript Operators

Today's Key Takeaways 🎯

You Can Now:

Next Class: Strings, conditionals, and more complex data types!