Week 4 Notes PDF
Document Details

Uploaded by DextrousMendelevium
The University of Winnipeg
Tags
Summary
These notes cover fundamental JavaScript concepts, including variables, data types, and basic operators. It includes examples and explanations of JavaScript syntax and different data types.
Full Transcript
**1. JavaScript in HTML** - JavaScript code can be embedded using the \ tag in an HTML document. - Example: - The code inside the \ tag is executed automatically when the browser processes it. **2. Modern \ Tag** - The type and language attributes are **not required** in modern...
**1. JavaScript in HTML** - JavaScript code can be embedded using the \ tag in an HTML document. - Example: - The code inside the \ tag is executed automatically when the browser processes it. **2. Modern \ Tag** - The type and language attributes are **not required** in modern HTML. - Example of a modern \ tag: **3. External Scripts** - JavaScript code can be placed in an external file and linked using the src attribute. - Example: - Benefits of external scripts: - **Caching**: The browser downloads the script once and caches it, improving page load speed for subsequent visits. - **Separation of concerns**: Keeps HTML clean and separates JavaScript logic. **4. Rules for \ Tags** - A \ tag **cannot have both src and internal code**. If src is used, the internal code is ignored. - Example of incorrect usage: - Correct usage: **5. Key Points to Remember** - Use \ to embed or link JavaScript in HTML. - External scripts are preferred for larger or reusable code. - The type and language attributes are outdated and unnecessary in modern HTML. - Caching of external scripts improves performance. **1. Variables in JavaScript** - A **variable** is a named storage for data. - Use the let keyword to declare a variable: - Assign a value to a variable using the = operator: - Combine declaration and assignment in one line: **2. Variable Naming Rules** - Variable names can contain: - Letters (a-z, A-Z), - Digits (0-9), - Symbols (\$ and \_). - The first character **cannot be a digit**. - Examples of valid names: - Examples of invalid names: **3. Case Sensitivity** - Variable names are **case-sensitive**: **4. Constants** - Use const to declare a constant (a variable that cannot be reassigned): - Attempting to reassign a constant will cause an error: **5. Uppercase Constants** - Use uppercase names for constants that are known before execution (e.g., hard-coded values): - This makes the code more readable and avoids typos **6. Variable Naming Best Practices** - Use **human-readable names**: - Avoid **abbreviations** or **short names** unless they are obvious: - Make names **descriptive** and **concise**: **8. Summary of Variable Declarations** - Use let for variables that can change: - Use const for variables that should not change: **Key Points to Remember** 1. **Declare variables** using let or const. 2. **Name variables** descriptively and follow naming conventions. 3. **Constants** (const) cannot be reassigned. 4. **Uppercase constants** are used for hard-coded values. 5. Avoid reusing variables for different purposes. **Data Types in JavaScript** 1. **Overview of Data Types** - A value in JavaScript is always of a certain type (e.g., string, number). - JavaScript is a **dynamically typed** language, meaning variables are not bound to a specific type and can change types. **Number Type** - Represents both **integer** and **floating-point** numbers. - Supports operations like multiplication (\*), division (/), addition (+), and subtraction (-). **Special Numeric Values** - **Infinity**: Represents mathematical infinity (∞). - **NaN**: Represents a computational error (e.g., invalid math operations). - **NaN is sticky**: Any operation involving NaN results in NaN. - Exception: NaN \*\* 0 equals 1. **String Type** - Quotes must surround a string in JavaScript. - Three types of quotes: 1. **Double quotes**: \"Hello\" 2. **Single quotes**: \'Hello\' 3. **Backticks**: \`Hello\` - Example: **Backticks for Embedding** - Backticks allow embedding variables and expressions using \${\...}. - Example: - **Note**: This functionality is only available with backticks. Double or single quotes do not support embedding. **Boolean Type** - The boolean type has two values: true and false. - Used for yes/no values: - Boolean values often result from comparisons: **Null Value** - The null value represents \"nothing,\" \"empty,\" or \"value unknown.\" - It forms its own type: **Undefined Value** - The undefined value means \"value is not assigned.\" - If a variable is declared but not assigned, its value is undefined: - **Note**: Avoid explicitly assigning undefined. Use null for \"empty\" or \"unknown\" values instead. **The typeof Operator** - The typeof operator returns the type of the operand as a string. - It is useful for checking the type of a value or variable. **Examples of typeof** **Key Points to Remember** 1. **typeof Behavior**: - Returns the type of the operand as a string. 2. **Special Cases**: - **typeof null**: Returns \"object\" (a historical bug in JavaScript). - **typeof alert**: Returns \"function\", even though functions are technically objects. 3. **Common Use Cases**: - Checking if a variable is undefined: - Differentiating between types: **Interaction: alert, prompt, confirm** - These are browser-specific functions used to interact with users. **1. alert** - Displays a message in a modal window and waits for the user to press \"OK\". - Example: - **Modal Window**: Pauses script execution and prevents interaction with the rest of the page until the user dismisses the window. **2. prompt** - Displays a modal window with a message, an input field, and buttons (OK/Cancel). - Syntax: - title: The message to display. - default (optional): The initial value for the input field. - Returns: - The text entered by the user if they press \"OK\". - null if the user cancels or presses Esc. - Example: - **Note**: Always provide a default value for compatibility with Internet Explorer. **3. confirm** - Displays a modal window with a question and two buttons: \"OK\" and \"Cancel\". - Syntax: - Returns: - true if the user presses \"OK\". - false if the user presses \"Cancel\" or Esc. - Example: **Summary of Interaction Methods** **Method** **Purpose** **Returns** ------------ ------------------------------------------------------------------------ ------------------------------ alert Shows a message and waits for the user to press \"OK\". None. prompt Shows a message, asks for input, and returns the entered text or null. Text or null. confirm Shows a message with \"OK\" and \"Cancel\" buttons. true (OK) or false (Cancel). **Key Points to Remember** 1. **Modal Windows**: - Pause script execution and block interaction with the page until dismissed. 2. **Limitations**: - The appearance and location of the modal window are controlled by the browser. - Cannot be customized. **Type Conversions in JavaScript** - JavaScript automatically converts values to the required type in most cases. - Sometimes, explicit conversion is needed using functions like String(), Number(), and Boolean(). **1. String Conversion** - Occurs when a value needs to be represented as a string (e.g., in alert). - Use String(value) to explicitly convert a value to a string. - Example: - Conversion rules: - false → \"false\" - null → \"null\" - undefined → \"undefined **2. Numeric Conversion** - Occurs automatically in mathematical operations. - Use Number(value) to explicitly convert a value to a number. - Example: - Conversion rules: - undefined → NaN - null → 0 - true → 1, false → 0 - Strings: - Whitespace is trimmed. - Empty string → 0. - Invalid number → NaN. - Examples: **3. Boolean Conversion** - Occurs in logical operations or explicitly with Boolean(value). - Conversion rules: - Falsy values: 0, null, undefined, NaN, \"\" (empty string) → false. - All other values → true. - Examples: - **Note**: - \"0\" and \" \" (space-only strings) are true. **Summary of Type Conversions** **Conversion Type** **Function** **Key Rules** --------------------- ---------------- ------------------------------------------------------------------------- **String** String(value) Converts values to their string representation (e.g., true → \"true\"). **Numeric** Number(value) Converts values to numbers. undefined → NaN, null → 0. **Boolean** Boolean(value) Falsy values: 0, null, undefined, NaN, \"\". All others → true. **Math Operations in JavaScript** - JavaScript supports the following math operations: 1. **Addition (+)** 2. **Subtraction (-)** 3. **Multiplication (\*)** 4. **Division (/)** 5. **Remainder (%)** 6. **Exponentiation (\*\*)** **1. Remainder (%)** - The remainder operator (%) returns the remainder of an integer division. - Example: **2. Exponentiation (\*\*)** - The exponentiation operator (\*\*) raises a number to the power of another. - Example: - Can also be used for roots: **5. Assignment (=)** - The assignment operator (=) assigns a value to a variable and returns the assigned value. - Example: - Assignment can be used in expressions: **6. Chaining Assignments** - Assignments can be chained: - For readability, it's better to split into separate lines: **7. Modify-in-Place Operators** - Shortcut operators modify and assign in one step: - Other modify-in-place operators: -=, \*=, /=, etc. **8. Increment (++) and Decrement (\--)** - **Increment (++)**: Increases a variable by 1. - **Decrement (\--)**: Decreases a variable by 1. - Example: - **Prefix vs Postfix**: - **Prefix (++counter)**: Returns the new value. - **Postfix (counter++)**: Returns the old value. - Example: **9. Precedence of Increment/Decrement** - Increment/decrement has higher precedence than most arithmetic operators. - Example: **Key Points to Remember** 1. **String Concatenation**: + concatenates strings if one operand is a string. 2. **Arithmetic Operators**: -, \*, / convert operands to numbers. 3. **Assignment (=)**: Assigns a value and returns it. 4. **Modify-in-Place**: Use +=, -=, \*=, etc., for concise code. 5. **Increment/Decrement**: - ++ increases by 1. - \-- decreases by 1. - Prefix (++x) returns the new value. - Postfix (x++) returns the old value. #### 1. Basic Comparison Operators - \> (greater than), \< (less than) - \>= (greater than or equal to), \ \'A\' → true - \'Glow\' \> \'Glee\' → true - Case-sensitive (\'a\' \> \'A\' → true due to Unicode order). - The longer word is always greater than the shorter word #### 4. Comparisons Between Different Types - Strings and numbers: converted to numbers. - Booleans: true becomes 1, false becomes 0. #### 6. Strict Equality (===) - No type conversion. #### Null and undefined behavior - null == undefined → true - null === undefined → false - null \> 0 → false - null == 0 → false - null \>= 0 → true (because null converts to 0 for comparisons but not for ==) #### 8. undefined Comparisons (Always false) undefined \> 0 // false undefined \< 0 // false undefined == 0 // false #### 9. Best Practices - **Use = = = for predictable comparisons.** - **Avoid comparing null or undefined with \, \=**. **Instead, check them separately.** - **Null and undefined turn to 0 and NaN respectively only when \>,\=,\ - If condition is **true**, value1 is returned. - If condition is **false**, value2 is returned. **6. Chaining Ternary Operators** - Multiple conditions can be chained using ?. - Syntax: **7. Non-Traditional Use of ?** - The ternary operator can execute code based on a condition without assigning a value. - Example: - **Note**: This is less readable than using if-else. Use if-else for executing code blocks. **8. Best Practices** - Always use **curly braces {}** with if, even for single statements. It improves readability. - Use **parentheses** with the ternary operator for clarity: - Prefer if-else for complex logic and the ternary operator for simple assignments. **Summary Table:** **Concept** **Syntax** -------------------- ------------------------------------------------------------------------ if if (condition) { \... } else if (condition) { \... } else { \... } else if if (condition1) { \... } else if (condition2) { \... } else { \... } Ternary Operator ? let result = condition ? value1 : value2; Chaining ? let result = condition1 ? value1 : condition2 ? value2 : defaultValue; #### #### Logical Operators in JavaScript JavaScript has 3 logical operators: - \|\| (OR) - && (AND) - ! (NOT) These operators work with **any data type** and return **non-boolean values (except !)** when used with non-boolean types. ### **1. OR (**\|\|**)** **Behavior:** - Returns the first **truthy** value. - If all values are **falsy**, returns the last one. **Examples:** console.log(1 \|\| 0); // 1 (truthy) console.log(null \|\| 1); // 1 (first truthy value) console.log(null \|\| 0 \|\| 1); // 1 (first truthy) console.log(undefined \|\| null \|\| 0); // 0 (all falsy, last value) **Short-circuiting:** - If the first operand is **truthy**, it **stops execution** and returns that value. - The second operand is **not evaluated**. true \|\| console.log(\"Not printed\"); // Skips execution false \|\| console.log(\"Printed\"); // Executes **Usage:** - Set **default values**: ### **2. AND (**&&**)** **Behavior:** - Returns the first **falsy** value. - If all values are **truthy**, returns the last one. **Examples:** console.log(1 && 0); // 0 (first falsy value) console.log(1 && 5); // 5 (both truthy, last value returned) console.log(null && 5); // null (first falsy) console.log(1 && 2 && null && 3); // null (first falsy) console.log(1 && 2 && 3); // 3 (all truthy, last value) **Short-circuiting:** - If the first operand is **falsy**, it **stops execution** and returns that value. - The second operand is **not evaluated**. false && console.log(\"Not printed\"); // Stops true && console.log(\"Printed\"); // Executes ### **3. NOT (**!**)** **Behavior:** - Converts the operand to a **boolean**. - Returns the **inverse** boolean value. **Examples:** console.log(!true); // false console.log(!0); // true console.log(!\"\"); // true (empty string is falsy) console.log(!\"text\"); // false (non-empty string is truthy) **Double NOT (!!):** - Converts any value into a **boolean**. console.log(!!\"non-empty string\"); // true console.log(!!null); // false console.log(!!0); // false console.log(!!1); // true **Usage:** - **Check if a variable has a value**: ### **4. Operator Precedence** **Order of execution:** 1. ! (NOT) -- **Highest precedence** 2. && (AND) 3. \|\| (OR) -- **Lowest precedence** **Example:** console.log(true \|\| false && false); // true (AND executes first) console.log((true \|\| false) && false); // false (Parentheses change order) ### **Key Takeaways** ✅ \|\| returns the **first truthy** value or the **last falsy** if none are truthy.\ ✅ && returns the **first falsy** value or the **last truthy** if none are falsy.\ ✅ ! negates the value and converts it to a boolean.\ ✅ **Short-circuiting** improves performance (stops evaluating once the result is determined).\ ✅ **Use !! for explicit boolean conversion**.\ ✅ **Operator precedence:** ! \ && \> \|\|. ### **JavaScript Loops** Loops are used to execute the same code multiple times. JavaScript provides three basic types of loops: - **while loop** - **do\...while loop** - **for loop** 1. The while Loop ----------------- while (condition) { // loop body } - Executes **while** the condition is **truthy**. - The **condition** is checked before each iteration. - If the condition is **false** at the start, the loop **never runs**. let i = 0; while (i \< 3) { console.log(i); // Outputs: 0, 1, 2 i++; } ### **Single-line** while **loop (no curly braces)**: let i = 3; while (i) console.log(i\--); // Outputs: 3, 2, 1 2. The do\...while Loop ----------------------- - Executes the loop body **at least once**, then checks the condition. - The **condition** is checked **after** each iteration. ### do { // loop body } while (condition); ### **Example:** let i = 0; do { console.log(i); // Outputs: 0, 1, 2 i++; } while (i \< 3); - Even if i starts as **3**, the body **executes once** before stopping. 3. The for Loop --------------- - Most commonly used loop. - **Has 3 parts**: 1. **Initialization (begin)** → Runs once at the start. 2. **Condition (condition)** → Checked before each iteration. 3. **Update (step)** → Runs after each iteration. ### **Syntax:** for (begin; condition; step) { // loop body } ### **Example:** for (let i = 0; i \< 3; i++) { console.log(i); // Outputs: 0, 1, 2 } **Execution steps:** 1. let i = 0 → Initialize i once. 2. i \< 3 → Check condition, if **true**, execute loop body. 3. console.log(i); → Print i. 4. i++ → Increment i and repeat until i \< 3 is false. 4. Variable Scope in for Loop ----------------------------- - If a variable is declared **inside** the for loop, it is **not accessible** outside. for (let i = 0; i \< 3; i++) { console.log(i); // 0, 1, 2 } console.log(i); // Error: i is not defined - If a variable is declared **outside**, it remains accessible after the loop. let i = 0; for (i = 0; i \< 3; i++) { console.log(i); // 0, 1, 2 } console.log(i); // 3 (still accessible) 5. Skipping Parts of a for Loop ------------------------------- - You can omit **any** of the three parts. ### **Omitting Initialization (**begin**)** let i = 0; for (; i \< 3; i++) { console.log(i); // 0, 1, 2 } ### **Omitting the Update (**step**)** let i = 0; for (; i \< 3;) { console.log(i); i++; // Must manually increment \`i\` } ### **Infinite** for **Loop** - Omitting all three parts creates an **infinite loop**: for (;;) { console.log(\"Runs forever!\"); } 6. while vs do\...while vs for ------------------------------ **Loop Type** **When to Use** ----------------- ---------------------------------------------------------------------------------- **while** When the number of iterations is **unknown** and depends on a **condition**. **do\...while** When you **must execute the loop body at least once**, regardless of condition. **for** When the number of iterations is **known** or when using a **counter variable**. ### **Key Takeaways** ✅ while(condition) runs **while** the condition is true.\ ✅ do\...while(condition) ensures **at least one execution**.\ ✅ for(begin; condition; step) is the **most commonly used loop**.\ ✅ **Short syntax** for single-line loops: while (i) console.log(i\--); ✅ **Skip parts in for loop**, but the semicolons (;) are required.\ ✅ **Avoid infinite loops!** Always ensure the loop condition eventually becomes false.