JS Essentials

Foundations · Prereqs: JS Intro: DOM + Events
--- theme: default routerMode: hash favicon: https://oim3690.github.io/favicon.svg titleTemplate: "%s - OIM3690" title: "JS Essentials" info: | const/let, primitive types, type conversion, function declarations, arrow functions, return vs console.log, if/else, comparison and logical operators, truthy/falsy basics <br><br> <b>Custom:</b> <kbd>t</kbd> Timer · <kbd>T</kbd> Start/pause · <kbd>w</kbd> Draw <br> <b>Slidev:</b> <kbd>o</kbd> Overview · <kbd>d</kbd> Dark mode · <kbd>f</kbd> Fullscreen · <kbd>←</kbd> <kbd>→</kbd> Navigate --- # JS Essentials Variables, Functions, and 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 sometimes 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 legacy code. When you see it, mentally replace it with `let` or `const`. **Rule for this course: never use `var`.** --- # 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 ``` --- # Objects An **object** groups related values as `key: value` pairs: ```js const student = { name: "Alice", grade: "A", }; // Access with dot notation console.log(student.name); // "Alice" student.grade = "A+"; // change a value ``` Arrays hold a **list**; objects hold **named fields**. You will often have an **array of objects**. --- # 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. --- # ▶️ typeof Run it. Note `typeof null` is `"object"`, a historical bug in JS: <script setup> const toJs = `console.log("typeof 'hello' =", typeof "hello"); console.log("typeof 42 =", typeof 42); console.log("typeof true =", typeof true); console.log("typeof undefined =", typeof undefined); console.log("typeof null =", typeof null);` </script> <CodePlayground console-only default-tab="js" :js="toJs" /> --- # 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. --- # ▶️ The String-Number Trap Type two numbers and click Add. You get `"53"`, not `8`, until you wrap with `Number()`: <script setup> const snHtml = `<input id="a" value="5" size="4"> + <input id="b" value="3" size="4"> <button id="go">Add</button> <p id="out" style="font-size: 1.4em; font-weight: bold;"></p>` const snJs = `document.querySelector("#go").addEventListener("click", function() { const a = document.querySelector("#a").value; // a string! const b = document.querySelector("#b").value; // a string! document.querySelector("#out").textContent = a + b; // "53", not 8 // Fix: Number(a) + Number(b) });` </script> <CodePlayground default-tab="js" :html="snHtml" :js="snJs" /> --- # 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 ``` --- 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. --- # ▶️ What Is a Function? Run it. Define once, call as many times as you like, edit the message: <script setup> const fnJs = `function greet() { console.log("Hello!"); } greet(); greet();` </script> <CodePlayground console-only default-tab="js" :js="fnJs" /> --- # Parameters vs Arguments These words are often confused. Here is the distinction: ```js // parameter (the variable name) // | 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, `return` for everything else.** --- # ▶️ return vs console.log Run it. The logging function returns `undefined`; only `return` gives a value you can use: <script setup> const rlJs = `function addAndLog(a, b) { console.log("inside addAndLog:", a + b); } const r1 = addAndLog(5, 3); console.log("addAndLog returned:", r1); function addAndReturn(a, b) { return a + b; } const r2 = addAndReturn(5, 3); console.log("addAndReturn returned:", r2);` </script> <CodePlayground console-only default-tab="js" :js="rlJs" /> --- # 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 add(a, b) { return a + b; } // Arrow function (same thing) const add = (a, b) => { return a + b; }; // Short form (implicit return) const add = (a, b) => a + b; // One 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 `converter.html` in your **oim3690** repo: a Celsius input, a button, and a result. **By hand, no AI:** write the function yourself (`F = C × 9/5 + 32`). It must **return** the value: ```js function toFahrenheit(celsius) { // your code here } ``` Wire it up: `Number()` the input, call your function, show the result. Test `100` → `212`. **Then with AI:** make it a two-way converter, type in either box and the other updates, like Google's converter widget. Check it uses `Number()` and `return`. --- 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"); } ``` --- # 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 `!==`.** --- # ▶️ Strict vs Loose Equality Run it. `==` converts types (surprising), `===` does not: <script setup> const eqJs = `console.log('5 == "5" =>', 5 == "5"); console.log('5 === "5" =>', 5 === "5"); console.log("0 == false =>", 0 == false); console.log("0 === false =>", 0 === false); console.log("null == undefined =>", null == undefined); console.log("null === undefined =>", null === undefined);` </script> <CodePlayground console-only default-tab="js" :js="eqJs" /> --- 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"); } ``` --- # ▶️ Combining Operators Change the values, watch which conditions pass: <script setup> const coJs = `let age = 25; let hasLicense = true; let hasInsurance = false; if (age >= 18 && hasLicense && hasInsurance) { console.log("Can rent a car"); } else { console.log("Cannot rent (something is missing)"); }` </script> <CodePlayground console-only default-tab="js" :js="coJs" /> --- # 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. --- # ▶️ Truthy and Falsy `if (name)` uses truthy/falsy. Try `""`, `0`, `"Alice"`, `null`: <script setup> const tfJs = `const name = ""; if (name) { console.log("Hello, " + name); } else { console.log("No name provided"); }` </script> <CodePlayground console-only default-tab="js" :js="tfJs" /> --- # 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 `discount.html` in your **oim3690** repo. **By hand, no AI:** write a function that takes a cart total and whether the user is a member, and returns the discount percent. ```js function getDiscount(total, isMember) { // total >= 100 AND a member -> 20 // total >= 100 OR a member -> 10 // otherwise -> 0 // your code here } ``` Use `&&`, `||`, and `if / else if`. Test a few combinations. **Then with AI:** have it build a fuller checkout page (total input, member checkbox, discount applied, final price, some styling). Check the discount logic still matches yours. --- # 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