Unit 4 - Notes
CSE326
Unit 4: JavaScript Application Development
1. Incorporating JavaScript in HTML
JavaScript can be integrated into an HTML document in three primary ways: inside the <head> element, inside the <body> element, or using an external file.
1.1 Inside the HEAD Element
Placing JavaScript in the <head> section is typically used for functions that need to be defined before the user interacts with the page, or for scripts that do not manipulate the DOM directly upon loading.
Characteristics:
- Scripts load before the HTML body is rendered.
- Useful for declaring functions called by events later.
Example:
<!DOCTYPE html>
<html>
<head>
<title>JS in Head</title>
<script>
function sayHello() {
alert("Hello from the Head!");
}
</script>
</head>
<body>
<button onclick="sayHello()">Click Me</button>
</body>
</html>
1.2 Inside the BODY Element
Placing JavaScript at the bottom of the <body> element (just before the closing </body> tag) is the current best practice for improving page load speed.
Characteristics:
- The browser renders the HTML content (text, images, styles) first.
- The user sees the page content before the script parses, improving perceived performance.
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Placeholder Text</p>
<script>
document.getElementById("demo").innerHTML = "Text changed by JS in Body";
</script>
</body>
</html>
1.3 Using an External JavaScript File
External scripts separate HTML (structure) from JavaScript (behavior). This is the standard for professional development.
Characteristics:
- Reusability: The same script can be used across multiple HTML pages.
- Maintainability: Code is easier to read and debug.
- Caching: Browsers can cache the external
.jsfile, speeding up subsequent page loads.
File: script.js
function externalFunction() {
alert("This is from an external file.");
}
File: index.html
<!DOCTYPE html>
<html>
<body>
<!-- The src attribute specifies the path to the external file -->
<script src="script.js"></script>
<button onclick="externalFunction()">Run External Script</button>
</body>
</html>
2. Variables: var, let, and const
In modern JavaScript (ES6+), there are three ways to declare variables. Understanding the scope and mutability of each is crucial.
2.1 var
The traditional way to declare variables.
- Scope: Function-scoped (if declared inside a function) or Global-scoped. It ignores block scope (e.g., inside
iforfor). - Hoisting: Variables are hoisted to the top of their scope and initialized with
undefined. - Re-declaration: Can be re-declared within the same scope.
2.2 let
The modern standard for variables that change.
- Scope: Block-scoped (exists only within the
{}it is defined in). - Hoisting: Hoisted but not initialized (accessing before declaration causes a ReferenceError).
- Re-declaration: Cannot be re-declared in the same scope.
2.3 const
Used for constants.
- Scope: Block-scoped.
- Mutability: The variable identifier cannot be reassigned. However, if the variable holds an object or array, the contents of that object/array can still be modified.
- Initialization: Must be initialized at the time of declaration.
Comparison Example:
function scopeTest() {
if (true) {
var a = "I am var"; // Function scoped
let b = "I am let"; // Block scoped
const c = "I am const"; // Block scoped
}
console.log(a); // Output: "I am var"
// console.log(b); // Error: b is not defined
// console.log(c); // Error: c is not defined
}
3. Operators
JavaScript supports various operators to manipulate data.
3.1 Arithmetic Operators
Used for mathematical calculations.
+(Addition),-(Subtraction),*(Multiplication),/(Division)%(Modulus/Remainder)++(Increment),--(Decrement)
3.2 Assignment Operators
Assigns values to variables.
=,+=,-=,*=,/=
3.3 Comparison Operators
Used in logical statements to determine equality or difference.
==: Equal to (value only).5 == "5"is true.===: Strict Equal to (value AND type).5 === "5"is false.!=: Not equal (value).!==: Strict Not equal (value or type).>,<,>=,<=
3.4 Logical Operators
&&(Logical AND): True if both operands are true.||(Logical OR): True if at least one operand is true.!(Logical NOT): Inverses the boolean value.
4. Control Statements
Control structures direct the flow of program execution based on conditions.
4.1 if...else Statement
Executes a block of code if a specified condition is true.
let hour = 14;
if (hour < 12) {
console.log("Good Morning");
} else if (hour < 18) {
console.log("Good Afternoon");
} else {
console.log("Good Evening");
}
4.2 switch Statement
Used to select one of many code blocks to be executed. It is often cleaner than many else if statements.
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Unknown Day";
}
console.log(dayName); // Output: Wednesday
4.3 break and continue
break: "Jumps out" of a loop or a switch statement immediately.continue: "Jumps over" one iteration in the loop and proceeds to the next iteration.
// Example of Break
for (let i = 0; i < 10; i++) {
if (i === 5) { break; } // Loop stops entirely when i is 5
console.log(i);
}
// Example of Continue
for (let i = 0; i < 5; i++) {
if (i === 2) { continue; } // Skips printing 2, but continues to 3
console.log(i);
}
5. Looping Statements
Loops are used to execute the same block of code a specified number of times or while a specified condition is true.
5.1 for Loop
The most common loop, used when the number of iterations is known.
Syntax: for (initialization; condition; increment/decrement) { ... }
for (let i = 0; i < 5; i++) {
console.log("Iteration number: " + i);
}
5.2 while Loop
Loops through a block of code as long as a specified condition is true.
Note: If the condition is never false, this creates an infinite loop.
let i = 0;
while (i < 5) {
console.log("While loop: " + i);
i++;
}
5.3 do...while Loop
Similar to the while loop, but this loop will execute the code block once before checking if the condition is true, then it will repeat the loop as long as the condition is true.
let i = 0;
do {
console.log("This runs at least once even if condition is false");
i++;
} while (i < 0); // Condition is false, but block ran once.
6. Popup Boxes
JavaScript provides three built-in global functions to interact with the user via system dialogs.
6.1 Alert Box
Used to ensure information comes through to the user. The user must click "OK" to proceed.
alert("This is an alert box! Execution pauses until you click OK.");
6.2 Confirm Box
Used to verify or accept something. It returns a Boolean value.
- Clicking "OK" returns
true. - Clicking "Cancel" returns
false.
let result = confirm("Do you want to delete this file?");
if (result) {
console.log("User clicked OK");
} else {
console.log("User clicked Cancel");
}
6.3 Prompt Box
Used if you want the user to input a value before entering a page.
- Clicking "OK" returns the input text.
- Clicking "Cancel" returns
null.
let person = prompt("Please enter your name:", "Harry Potter");
if (person != null) {
console.log("Hello " + person);
}
7. Working with JavaScript Objects
Objects are the fundamental data structure in JavaScript. They allow you to store collections of data (properties) and functionality (methods).
7.1 Creating Objects
The most common way to create an object is using the Object Literal syntax {}.
const student = {
firstName: "John",
lastName: "Doe",
age: 20,
course: "Computer Science"
};
7.2 Object Properties
Properties are values associated with a JavaScript object.
Accessing Properties:
- Dot Notation:
objectName.propertyName - Bracket Notation:
objectName["propertyName"](Useful if keys have spaces or are dynamic variables).
console.log(student.firstName); // Output: John
console.log(student["course"]); // Output: Computer Science
7.3 Object Methods
Methods are actions that can be performed on objects. A method is essentially a function stored as a property.
The this Keyword:
In an object method, this refers to the object itself.
const car = {
brand: "Toyota",
model: "Camry",
year: 2022,
// Defining a method
getDetails: function() {
// 'this' refers to the 'car' object
return this.brand + " " + this.model + " (" + this.year + ")";
}
};
// Calling the method
console.log(car.getDetails()); // Output: Toyota Camry (2022)
7.4 Adding/Modifying Properties
Objects are mutable. You can add new properties or change existing ones after creation.
const book = { title: "JS Guide" };
// Add new property
book.author = "Jane Doe";
// Modify existing property
book.title = "Advanced JS Guide";
console.log(book); // { title: "Advanced JS Guide", author: "Jane Doe" }