JS Fundamentals: Variables, Functions, Conditionals

Foundations · Prereqs: F-JS-001
--- theme: seriph title: "JS Fundamentals: Variables, Functions, Conditionals" info: "Module F-JS-002/003: const/let, primitive types, type conversion, function declarations, arrow functions, return vs console.log, if/else, comparison and logical operators, truthy/falsy basics" --- # JS Fundamentals: Variables, Functions, Conditionals --- # Variables: Naming a Value A variable is a **label** that points to a value stored in memory. ```js const courseName = "OIM3690"; let weekNumber = 1; ``` You **declare** a variable once, then **use** it by name. --- # const vs let Two keywords, two rules: ```js // const: value cannot be reassigned const maxScore = 100; maxScore = 200; // TypeError: Assignment to constant variable // let: value can be reassigned let currentScore = 0; currentScore = 75; // OK ``` **Default to `const`.** Only use `let` when you know the value will change. > AI tip: AI often uses `let` where `const` would work. Check: does the variable get reassigned later? If not, change it to `const`. --- # Why Not var? `var` is the old way. It has scoping quirks that cause bugs. ```js var x = 10; // works, but don't use it let y = 20; // use this instead const z = 30; // or this ``` You will see `var` in older tutorials and AI-generated code. When you see it, mentally replace it with `let` or `const`. > **Rule for this course:** never use `var`. > AI tip: If AI generates `var`, replace it with `const` (or `let` if the value gets reassigned). --- # const Does Not Mean "Unchangeable" `const` prevents **reassignment**, not **mutation**. ```js const scores = [90, 85, 92]; scores.push(88); // OK, mutating the array scores = [100, 95]; // TypeError, reassigning the variable const student = { name: "Alice" }; student.name = "Bob"; // OK, mutating the object student = {}; // TypeError, reassigning the variable ``` Think of `const` as "this label always points to the same box." You can change what's *inside* the box, but not *which* box. --- # Variable Naming **Rules:** - Start with a letter, `_`, or `$` - No spaces or special characters - Case sensitive (`myVar` !== `myvar`) **Conventions:** - `camelCase` for variables: `userName`, `totalScore` - `UPPER_CASE` for true constants: `MAX_SIZE`, `API_KEY` ```js const firstName = "Alice"; // camelCase const MAX_RETRIES = 3; // UPPER_CASE constant ``` --- layout: center --- # Data Types --- # Primitive Types JavaScript has a few basic types. You will use three of them constantly. ```js // String (text) const name = "Alice"; // Number (integers and decimals) const age = 25; const price = 19.99; // Boolean (true or false) const isStudent = true; ``` Two more you will encounter: ```js let x; // undefined: no value assigned yet const y = null; // null: intentionally empty ``` --- # Checking Types with typeof ```js typeof "hello" // "string" typeof 42 // "number" typeof true // "boolean" typeof undefined // "undefined" typeof null // "object" (historical bug in JS) ``` `typeof` is useful for debugging when a value is not what you expected. --- # Strings: Template Literals Use backticks for strings that include variables or span multiple lines. ```js const name = "Alice"; const age = 25; // Concatenation (old way) const msg1 = "Hello, " + name + "! You are " + age + "."; // Template literal (preferred) const msg2 = `Hello, ${name}! You are ${age}.`; ``` **Use template literals.** They are easier to read, especially in HTML. --- # The String-Number Trap **Form inputs are always strings**, even when they look like numbers. ```js const input = document.querySelector("#age").value; typeof input; // "string", always! // This goes wrong: input + 10; // "2510" (string concatenation, not math) // Fix: convert first Number(input) + 10; // 35 (actual addition) ``` This is the #1 source of bugs in student projects. > AI tip: When AI writes form code, verify it uses `Number()` on input values before doing math. AI sometimes skips this step. --- # Type Conversion ```js // String to Number Number("42") // 42 Number("hello") // NaN (Not a Number) Number("") // 0 Number(true) // 1 // Number to String String(42) // "42" // Check for NaN Number.isNaN(Number("hello")) // true ``` > **Tip:** When reading form input, always `Number()` before doing math. --- layout: center --- # Functions --- # What Is a Function? A **reusable block of code** that performs a task. ```js // Define function greet() { console.log("Hello!"); } // Call greet(); // prints "Hello!" greet(); // prints "Hello!" again ``` Define once, call many times. --- # Parameters vs Arguments These words are often confused. Here is the distinction: ```js // parameter (the placeholder) // | function greet(name) { console.log(`Hello, ${name}!`); } greet("Alice"); // "Alice" is the argument (the actual value) greet("Bob"); // "Bob" is the argument ``` - **Parameter**: the variable name in the function definition - **Argument**: the actual value you pass when calling the function --- # Multiple Parameters ```js function add(a, b) { return a + b; } add(5, 3); // 8 add(10, 20); // 30 ``` Parameters are listed in order. The first argument maps to the first parameter. --- # return vs console.log This is the most common confusion. They do completely different things. ```js // console.log: prints to the console (for debugging) function addAndLog(a, b) { console.log(a + b); // shows 8 in the console } const result1 = addAndLog(5, 3); // result1 is undefined! // return: sends the value back to the caller function addAndReturn(a, b) { return a + b; // gives 8 back to the caller } const result2 = addAndReturn(5, 3); // result2 is 8 ``` --- # return vs console.log: The Rule `console.log` is like **shouting the answer into the room**. Everyone hears it, but nobody can use it. `return` is like **handing the answer to the person who asked**. They can store it, pass it along, or do math with it. ```js function getTotal(price, tax) { return price + tax; } // You can use the returned value const total = getTotal(100, 8); const message = `Your total is $${total}`; ``` > **Rule:** Use `console.log` for debugging. Use `return` for everything else. > AI tip: AI-generated functions sometimes use `console.log` instead of `return`. If you need to use the result later, make sure the function returns it. --- # Arrow Functions A shorter syntax for writing functions. AI-generated code uses them constantly. > AI tip: When AI writes `const fn = (x) => x * 2`, that is an arrow function. Read `=>` as "takes ... and returns ...". ```js // Traditional function function add(a, b) { return a + b; } // Arrow function const add = (a, b) => { return a + b; }; // Short form (implicit return, one expression) const add = (a, b) => a + b; // Single parameter (parentheses optional) const double = x => x * 2; ``` --- # When to Use Which Syntax | Style | Use when | |---|---| | `function name() {}` | Standalone, named functions | | `const name = () => {}` | Storing in a variable, callbacks | | `() => expression` | Short one-liners (map, filter) | For this course, either style is fine. Just be consistent within a file. --- # Functions as Event Handlers You will attach functions to HTML elements with `addEventListener`. ```js // Named function function handleClick() { console.log("Clicked!"); } button.addEventListener("click", handleClick); // Arrow function (inline) button.addEventListener("click", () => { console.log("Clicked!"); }); ``` Notice: `handleClick` without `()`. You pass the function, you do not call it. --- # Your Turn Create `adder.html` in your course repo. Build a page with two `<input>` fields and a button. When clicked, add the two numbers and display the result. **The trap:** without conversion, `"5" + "3"` gives `"53"`, not `8`. ```js button.addEventListener("click", () => { const a = Number(document.querySelector("#num1").value); const b = Number(document.querySelector("#num2").value); const sum = a + b; document.querySelector("#result").textContent = sum; }); ``` Test: enter `5` and `3`. If you see `53`, you forgot `Number()`. --- layout: center --- # Conditionals --- # What Are Conditionals? Conditionals let your code make **decisions**: - If the user is logged in, show their profile - If the form is invalid, show an error - If the score is high enough, show "You Win!" --- # Basic if / if...else The condition must be in parentheses. The code block runs only when the condition is true. ```js let age = 20; if (age >= 18) { console.log("You are an adult"); } ``` Use `else` when you have exactly two paths: ```js if (age >= 18) { console.log("Adult"); } else { console.log("Minor"); } ``` > AI tip: AI-generated conditionals are usually correct, but always trace through them with a test value to make sure. --- # if...else if...else Conditions are checked in order. The first true condition runs and the rest are skipped. ```js let score = 85; if (score >= 90) { console.log("A"); } else if (score >= 80) { console.log("B"); } else if (score >= 70) { console.log("C"); } else if (score >= 60) { console.log("D"); } else { console.log("F"); } ``` --- # Comparison Operators Always use `===` (strict equality) to avoid unexpected type conversions. | Operator | Meaning | |---|---| | `===` | Equal (strict) | | `!==` | Not equal (strict) | | `>` | Greater than | | `<` | Less than | | `>=` | Greater than or equal | | `<=` | Less than or equal | --- # Strict vs Loose Equality ```js // Loose equality (==): converts types 5 == "5" // true (string converted to number) 0 == false // true null == undefined // true // Strict equality (===): no conversion 5 === "5" // false (different types) 0 === false // false null === undefined // false ``` > **Always use `===` and `!==`** > AI tip: AI sometimes generates `==` instead of `===`. Always change it to strict equality (`===`). --- layout: center --- # Logical Operators --- # AND (&&) / OR (||) / NOT (!) **AND**: both must be true: ```js if (age >= 21 && hasID) { console.log("Can enter the bar"); } ``` **OR**: at least one must be true: ```js if (isStudent || isSenior) { console.log("Eligible for discount"); } ``` **NOT**: reverses a condition: ```js if (!isLoggedIn) { console.log("Please log in"); } ``` --- # Combining Operators Use parentheses to group conditions for clarity. ```js let age = 25; let hasLicense = true; let hasInsurance = true; if (age >= 18 && hasLicense && hasInsurance) { console.log("Can rent a car"); } // Parentheses make grouping explicit if ((age >= 18 && age <= 65) || isExempt) { console.log("Eligible"); } ``` --- # Truthy and Falsy These six values are **falsy**. Everything else is truthy: ```js false 0 "" // empty string null undefined NaN ``` > AI tip: AI often writes `if (name)` instead of `if (name !== "")`. Both work because of truthy/falsy, but now you know why. Use this for concise checks: ```js let name = ""; if (name) { console.log(`Hello, ${name}`); } else { console.log("No name provided"); } ``` --- # Ternary Operator Shorthand for simple if/else. Use only for brief assignments, not complex logic. > AI tip: AI loves ternary operators. Learn to read them, but write `if/else` when starting out. ```js // condition ? valueIfTrue : valueIfFalse let age = 20; let status = age >= 18 ? "adult" : "minor"; // Equivalent to: let status2; if (age >= 18) { status2 = "adult"; } else { status2 = "minor"; } ``` --- # Your Turn Create `number-check.html` in your course repo. Write a function that takes a number and returns `"positive"`, `"negative"`, or `"zero"`. ```js function checkNumber(num) { // Your code here } // Test it console.log(checkNumber(5)); // "positive" console.log(checkNumber(-3)); // "negative" console.log(checkNumber(0)); // "zero" ``` --- # Key Takeaways 1. **`const` by default**, `let` when needed, **never `var`** 2. `const` prevents reassignment, not mutation 3. Form inputs are **always strings**, convert with `Number()` 4. **Parameters** are placeholders; **arguments** are actual values 5. **`return`** gives a value back; **`console.log`** only prints 6. Arrow functions are shorthand; learn to read them 7. `if / else if / else` is the core decision structure 8. Always use `===` and `!==` (strict equality) 9. `&&` (AND), `||` (OR), `!` (NOT) combine conditions 10. Six falsy values: `false`, `0`, `""`, `null`, `undefined`, `NaN` 11. Ternary (`? :`) for simple one-line decisions --- # References - [MDN: if...else](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) - [MDN: Comparison Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) - [JavaScript.info: Conditionals](https://javascript.info/ifelse) --- # Reference: switch You may see `switch` in AI-generated code. It compares one value against multiple cases. You do not need it often since `if/else if` covers the same situations. ```js let day = "Monday"; switch (day) { case "Monday": console.log("Start of work week"); break; case "Friday": console.log("TGIF!"); break; default: console.log("Regular day"); } ```

Topics Covered

  • const/let (no var)
  • primitive types
  • string vs number
  • Number() conversion
  • function declarations and arrow functions
  • parameters vs arguments
  • return vs console.log
  • if/else
  • comparison and logical operators
  • truthy/falsy basics

Content Slides Open fullscreen ↗

Taught In

  • Monday, 6/15 — MP1 showcase · JS variables, types, functions · AI debugging
  • Wednesday, 6/17 — JS conditionals · arrays + loops