Day 19 - JavaScript Data Types & Conditionals

JavaScript Foundations

Data Types & Conditionals 🎯

CSCI 3403 - Web Programming

Day 19

Time to make our programs think! 🧠

Today's Learning Objectives 🎯

Note: We'll do the first two exercises in class, rest are homework!

The Eight Data Types 🎱

JavaScript's Building Blocks

Primitives (7)

  • number - 42, 3.14
  • string - "Hello"
  • boolean - true/false
  • undefined - not assigned
  • null - intentionally empty
  • symbol - unique identifier
  • bigint - huge numbers

Non-Primitive (1)

  • object - Complex data
  • Arrays: [1, 2, 3]
  • Objects: {name: "John"}
  • Functions
  • Dates

Working with Strings 📝

Three Types of Quotes

// Single quotes
let single = 'Hello World';

// Double quotes  
let double = "Hello World";

// Backticks (template literals) - SPECIAL!
let name = "Alice";
let greeting = `Hello, ${name}!`;  // "Hello, Alice!"
let multiline = `This is
a multiline
string`;
                
Pro Tip: Backticks (`) allow variables and expressions inside with ${...}

String Methods 🔧

Built-in String Superpowers!

let text = "JavaScript is awesome!";

// Length property
console.log(text.length);           // 22

// Change case
console.log(text.toUpperCase());    // "JAVASCRIPT IS AWESOME!"
console.log(text.toLowerCase());    // "javascript is awesome!"

// Extract parts
console.log(text.slice(0, 10));     // "JavaScript"
console.log(text.substring(0, 10)); // "JavaScript"

// Find and replace
console.log(text.indexOf("is"));    // 11
console.log(text.replace("awesome", "fun")); // "JavaScript is fun!"
                

Joining Strings Together 🔗

Old Way (Concatenation)

let firstName = "John";
let lastName = "Doe";
let age = 25;

let message = "Hello, my name is " + 
              firstName + " " + lastName + 
              " and I am " + age + " years old.";
                        

Modern Way (Template Literals)

let firstName = "John";
let lastName = "Doe";
let age = 25;

let message = `Hello, my name is ${firstName} ${lastName} 
               and I am ${age} years old.`;
                        

Escape Characters 🚪

When You Need Special Characters

// Quotes inside quotes
let quote1 = "She said, \"Hello!\"";
let quote2 = 'It\'s a beautiful day';

// Special characters
let newLine = "First line\nSecond line";
let tab = "Column1\tColumn2\tColumn3";
let backslash = "C:\\Users\\Documents";

// Or use different quotes
let easier = 'She said, "Hello!"';
let easier2 = "It's a beautiful day";
                
Common Escapes: \n (new line), \t (tab), \\ (backslash), \" (quote), \' (apostrophe)

Comparison Operators ⚖️

Making Comparisons

Operator Description Example Result
== Equal to (loose) 5 == "5" true
=== Equal to (strict) 5 === "5" false
!= Not equal 5 != 3 true
>, < Greater/Less than 10 > 5 true
>=, <= Greater/Less or equal 5 >= 5 true
Best Practice: Always use === for comparisons unless you have a specific reason not to!

Logical Operators 🔀

Combining Conditions

// AND (&&) - Both must be true
let age = 25;
let hasLicense = true;
let canDrive = age >= 16 && hasLicense;  // true

// OR (||) - At least one must be true
let isWeekend = false;
let isHoliday = true;
let dayOff = isWeekend || isHoliday;  // true

// NOT (!) - Flips the boolean
let isRaining = false;
let isSunny = !isRaining;  // true

// Combining operators
let canEnter = (age >= 18 && hasTicket) || isVIP;
                

Truthy vs Falsy ✅❌

JavaScript's Hidden Booleans

❌ Falsy Values (Only 6!)

  • false
  • 0 (zero)
  • "" (empty string)
  • null
  • undefined
  • NaN (Not a Number)

✅ Truthy Values

  • true
  • Any number (except 0)
  • Any string (except "")
  • All objects and arrays
  • "false" (string)
  • "0" (string)
if ("hello") console.log("This runs!");     // Truthy
if (0) console.log("This doesn't run");      // Falsy

If/Else Statements 🚦

Making Decisions in Code

// Basic if statement
let score = 85;
if (score >= 90) {
    console.log("A grade!");
} else if (score >= 80) {
    console.log("B grade!");
} else if (score >= 70) {
    console.log("C grade!");
} else {
    console.log("Keep studying!");
}

// With logical operators
let age = 19;
let hasPermission = true;

if (age >= 18 && hasPermission) {
    console.log("Access granted!");
} else {
    console.log("Access denied!");
}
                

Nesting Conditionals 🪆

Conditions Inside Conditions

let isLoggedIn = true;
let userRole = "admin";
let hasPermission = true;

if (isLoggedIn) {
    console.log("User is logged in");
    
    if (userRole === "admin") {
        console.log("Welcome, Admin!");
        
        if (hasPermission) {
            console.log("Full access granted");
        } else {
            console.log("Limited admin access");
        }
    } else {
        console.log("Welcome, User!");
    }
} else {
    console.log("Please log in");
}
                
Warning: Too much nesting makes code hard to read. Try to keep it under 3 levels!

Switch Statements 🎛️

Multiple Cases, One Variable

Many If/Else

let day = "Monday";

if (day === "Monday") {
    console.log("Start of work week");
} else if (day === "Friday") {
    console.log("TGIF!");
} else if (day === "Saturday" || 
           day === "Sunday") {
    console.log("Weekend!");
} else {
    console.log("Regular day");
}
                        

Switch Statement

let day = "Monday";

switch(day) {
    case "Monday":
        console.log("Start of work week");
        break;
    case "Friday":
        console.log("TGIF!");
        break;
    case "Saturday":
    case "Sunday":
        console.log("Weekend!");
        break;
    default:
        console.log("Regular day");
}
                        

Ternary Operator

If/Else in One Line!

// Syntax: condition ? ifTrue : ifFalse

// Instead of this:
let age = 20;
let message;
if (age >= 18) {
    message = "You can vote!";
} else {
    message = "Too young to vote";
}

// Use this:
let age = 20;
let message = age >= 18 ? "You can vote!" : "Too young to vote";

// More examples:
let score = 85;
let grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";

let isLoggedIn = true;
let greeting = `Welcome ${isLoggedIn ? "back" : "guest"}!`;
                
Use for: Simple if/else. Avoid for complex logic!

Exercise Time! 💻

Let's Code Together

We'll do in class:

  1. ✅ 01_helloWorld - Test our setup
  2. ✅ 02_addNumbers - Working with numbers

Homework (due next class):

  1. 📝 03_numberChecker
  2. 📝 04_mathEquations
  3. 📝 05_joinStrings
Remember: Read the README, watch the terminal, read the errors!

Exercise 1: Hello World 👋

Testing Our Setup

Steps:

  1. Fork the javascript-exercises repository
  2. Clone to your local machine
  3. Install Jest: npm install
  4. Navigate to 01_helloWorld folder
  5. Open helloWorld.js
// Your task: Make this function return "Hello, World!"
function helloWorld() {
    // Your code here
}

// Test with: npm test helloWorld
                
Let's do this together! I'll share my screen.

Exercise 2: Add Numbers

Working with Number Operations

// Your task: Make this function add two numbers
function add(a, b) {
    // Your code here
}

// Examples:
// add(2, 3) should return 5
// add(-1, 1) should return 0
// add(0.1, 0.2) should return 0.3 (approximately)

// Test with: npm test addNumbers
                
Hint: This one is simpler than you might think! What operator adds numbers?
Your turn! Try it yourself, I'll help if you get stuck.

Common Conditional Patterns 🎯

Patterns You'll Use Often

// Checking if something exists
if (username) {
    console.log(`Hello, ${username}`);
} else {
    console.log("Please enter a username");
}

// Default values
let name = inputName || "Anonymous";

// Range checking
if (age >= 13 && age <= 19) {
    console.log("You're a teenager!");
}

// Multiple conditions
if (day === "Saturday" || day === "Sunday" || isHoliday) {
    console.log("No work today!");
}

// Guard clauses (exit early)
function processUser(user) {
    if (!user) return "No user provided";
    if (!user.age) return "Age required";
    if (user.age < 18) return "Must be 18+";
    
    // Main logic here
    return "User processed!";
}
                

Debugging Conditionals 🐛

When Things Don't Work

Common Mistakes:

  • 🔍 Using = instead of === (assignment vs comparison)
  • 🔍 Forgetting break in switch statements
  • 🔍 Wrong operator precedence (use parentheses!)
  • 🔍 Truthy/falsy confusion (0, "", null are falsy)
// Debug with console.log!
let value = getUserInput();
console.log("Value is:", value);
console.log("Type is:", typeof value);
console.log("Truthy?", !!value);

if (value === "expected") {
    console.log("Match!");
} else {
    console.log("No match, value was:", value);
}
                

Quick Reference Card 📋

Data Types

  • number, string, boolean
  • undefined, null
  • symbol, bigint
  • object (includes arrays)

String Methods

  • .length, .toUpperCase()
  • .slice(), .replace()
  • .indexOf(), .includes()

Operators

  • ===, !== (strict)
  • &&, ||, ! (logical)
  • >, <, >=, <= (comparison)

Conditionals

  • if / else if / else
  • switch / case / default
  • condition ? true : false

Homework 📚

Complete Exercises 3-5

Due Next Class:

  • ✏️ 03_numberChecker - Use conditionals to check numbers
  • ✏️ 04_mathEquations - Solve math with operators
  • ✏️ 05_joinStrings - Practice string concatenation

Tips for Success:

  • Read the test files to understand what's expected
  • Run tests frequently: npm test exerciseName
  • Google is your friend - search for JavaScript methods!
  • Don't overthink - start simple, then refine

Great Work Today! 🎉

You've Learned:

Next Class: Functions and Scope!

Questions?