JavaScript's Role in Browser Object Model (BOM) and HTML Document Object Model (DOM)

Learning outcomes:

Applying JavaScript to building the web application
How does JavaScript work with Chromium in the Browser Object Model (BOM) and the HTML Document Object Model (DOM).

Node.js JavaScript Program: Illustrating `let`, Loops, and Conditional Statements

Learning outcomes:

Scoping in JavaScript

In this Node.js program, we will illustrate the use of `let`for variable declarations, and demonstrate `for`, `while` loops, and `if-then` conditional statements with variable comparisons.
**Loops:** - Use `for` and `while` loops to iterate over elements.
3. **Conditional Statements:** - Use `if-then` statements for variable comparisons.
#### Node.js JavaScript Code

// Illustrating for loop console.log("\nIllustrating for loop:");
for (let i = 0; i < 3; i++) { console.log("For loop iteration:", i); }
// Illustrating while loop console.log("\nIllustrating while loop:");
let whileCounter = 0; while (whileCounter < 3) { console.log("While loop iteration:", whileCounter); whileCounter++; }
// Illustrating if-then statements console.log("\nIllustrating if-then statements:");
let numberToCompare = 5; if (numberToCompare > 3) { console.log("The number is greater than 3."); } else { console.log("The number is not greater than 3."); } ```
`let` is block-scoped, meaning its scope is limited to the block (e.g., `if`, `for` blocks) it was declared in.
2. **Loops:** - The `for` loop iterates a set number of times, and the `while` loop continues until a certain condition is no longer true.
3. **Conditional Statements:** - The `if-then` statement checks if the condition (`numberToCompare > 3`) is true and executes the corresponding code block.
#### Running the Program
1. Create a new file named `example.js` in your Node.js environment. 2. Copy and paste the provided code into `example.js`. 3. Run the program in a terminal using `node example.js`.
This program offers a practical demonstration of some fundamental JavaScript concepts, which are crucial for developing more complex Node.js applications.

Lecture Lab Worksheet: let, var, and the the Temporal Dead Zone in JavaScript

#### Introduction Today's lab session focuses on a crucial aspect of JavaScript known as the "Temporal Dead Zone" (TDZ). This concept is essential for understanding how JavaScript handles variable declarations using `let` and `const`.
#### Objective - To understand the Temporal Dead Zone in JavaScript. - To illustrate how TDZ differs between `var`, `let`, and `const`.
#### Background The Temporal Dead Zone refers to the time from when a block-scoped variable (`let` or `const`) is hoisted until it is declared.
During this period, accessing the variable results in a `ReferenceError`. This concept is fundamental in understanding scope and hoisting in JavaScript.
#### Lab Exercises
**Exercise 1: Illustrating TDZ with `let`** 1. Create a JavaScript file, `tdz-let.js`. 2. Write the following code:
```javascript console.log(a); // Attempt to access 'a' before declaration let a = 3; ```
3. Run the file using Node.js and observe the output. 4. **Question:** Why does accessing `a` before its declaration result in an error?

**Exercise 2: TDZ with `const`** 1. Create a file, `tdz-const.js`. 2. Write the code:
```javascript console.log(c); // Attempt to access 'c' before declaration const c = 3; ```
3. Run and observe the result. 4. **Question:** Is the behavior the same as with `let`? Why or why not?
**Exercise 4: Temporal Dead Zone Duration** 1. Create a file, `tdz-duration.js`. 2. Write the following code:
```javascript { console.log(d); // Access within the TDZ let d = 5; console.log(d); // Access after declaration } ```
3. Run the file and analyze the output. 4. **Question:** At what point does the Temporal Dead Zone end for `d`?
#### Conclusion After completing these exercises, you should have a better understanding of the Temporal Dead Zone in JavaScript. This knowledge is vital for writing error-free code, particularly in understanding the scope and hoisting behaviors of `let` and `const`.
#### Further Discussion - Discuss how understanding TDZ can prevent common bugs in JavaScript programming. - Consider how the concept of TDZ aligns with best practices in declaring and using variables.
**Homework:** - Write a short paragraph on how the TDZ impacts variable hoisting in JavaScript. - Create a code snippet where properly understanding TDZ would prevent a runtime error.

What is JavaScript?

Definition: JavaScript is a powerful, high-level programming language primarily used in web development. It's a core technology of the World Wide Web, alongside HTML and CSS.
Characteristics: JavaScript is dynamic, interpreted, and supports object-oriented, imperative, and functional programming styles.
Purpose: It is used to create interactive and dynamic web pages, enhancing user experience by allowing web pages to respond to user actions.

JavaScript and the HTML Document Object Model (DOM)

DOM Overview: The DOM is a programming interface for HTML (and XML) documents. It represents the page so that programs can change the document structure, style, and content.
JavaScript's Role with DOM:
Manipulating HTML Elements: JavaScript can add, remove, or modify HTML elements in a page, essentially changing the content and structure of web documents dynamically.
Event Handling: JavaScript can respond to user actions (events), such as clicks, key presses, and mouse movements, allowing interaction with HTML elements.
Dynamic Styling: It can change the styles of HTML elements, like colors, sizes, and positions, making the page more dynamic and responsive to user inputs.

JavaScript and the Browser Object Model (BOM)

BOM Overview: The BOM provides objects that expose the functionality of the browser, allowing JavaScript to interact with the browser itself.
Key Elements of BOM:
Window Object: Represents a browser window or frame. It includes methods to control the window's appearance and response to user actions.
Location Object: Provides information about the current URL and methods to redirect the browser to another URL.
Navigator Object: Contains information about the browser, such as the name, version, and the platform it's running on.
Screen Object: Holds information about the user's screen, like its resolution.
JavaScript's Role with BOM:
Window Manipulation: JavaScript can open new windows, close existing ones, and control their size and position.
Browser Navigation: It allows navigation to new pages and manipulation of the browsing history.
User Environment Interaction: JavaScript can retrieve information about the user's screen and browser, aiding in creating responsive designs.

Practical Applications

Interactive Forms: Using JavaScript to validate form inputs in real-time before submission.
Pop-Up Windows: Creating and managing pop-up windows for alerts, warnings, or additional information.
Dynamic Content Loading: Using AJAX (Asynchronous JavaScript and XML) to load new content without refreshing the entire page.
Animations and Effects: Creating engaging visual effects and animations on web pages.


JavaScript's integration with the DOM and BOM is integral to modern web development. It bridges the gap between static HTML content and dynamic user interactions, allowing the creation of rich, interactive, and responsive web applications. As budding web developers, mastering JavaScript and its interactions with the DOM and BOM is essential for your journey in creating compelling and user-friendly websites.

Next Steps

In our upcoming sessions, we will explore hands-on exercises and projects that utilize JavaScript with the DOM and BOM, solidifying these concepts through practical application.

Lecture: The Mechanics of Chromium and JavaScript's Interaction with HTML DOM

#### Introduction Today, we'll explore the inner workings of Chromium and how JavaScript interacts with the HTML Document Object Model (DOM) to create, modify, and handle events within web pages.
#### Understanding Chromium - **What is Chromium?** - Chromium is an open-source web browser project from which Google Chrome draws its source code. It's pivotal in web development due to its wide usage and influence.
- **Chromium's Key Components:** - **Blink Engine:** The rendering engine used for displaying HTML, CSS, and executing JavaScript. - **V8 JavaScript Engine:** A high-performance JavaScript and WebAssembly engine that compiles JavaScript to native machine code before executing it.
- **Mechanics of Chromium:** - When a web page is loaded, Chromium's Blink engine processes the HTML, CSS, and JavaScript. - The HTML forms the DOM, CSS styles it, and JavaScript is used to make the page interactive.
#### JavaScript and the HTML DOM - **Role of JavaScript in DOM Manipulation:** - JavaScript can create, change, and remove HTML elements, attributes, and text content, enabling dynamic content modification.
- **Creating HTML Nodes:** - JavaScript can create new HTML elements/nodes using methods like `document.createElement()`, and add them to the DOM using methods like `appendChild()` or `insertBefore()`.
```javascript let newDiv = document.createElement("div"); document.body.appendChild(newDiv); ```
- **Modifying HTML Nodes:** - Existing nodes can be modified using properties and methods like `innerHTML`, `textContent`, or `setAttribute()`. ```javascript newDiv.innerHTML = "Hello, World!"; newDiv.setAttribute("class", "my-div"); ```
- **Event Handling:** - JavaScript reacts to user actions through event listeners. It can respond to events like clicks, keyboard input, or mouse movements. ```javascript newDiv.addEventListener("click", function() { alert("Div clicked!"); }); ```
#### Up Next In our following lectures, we will delve into advanced JavaScript DOM manipulation techniques and explore best practices for writing efficient, cross-browser compatible code. Stay engaged for more insights into mastering web development with JavaScript!

Simple JavaScript Programs to Illustrate the Use of the Console in Chromium Debugger

Below are five simple JavaScript programs that you can run in a `<script>` tag. These programs demonstrate different ways to utilize the console in the Chromium debugger for various purposes such as logging, error handling, and performance testing.
#### Program 1: Basic Logging ```html <script> console.log("Hello, World!");"This is an informational message."); console.warn("Warning! Something needs your attention."); console.error("Error occurred!"); </script> ``` **Description:** This program demonstrates the basic logging methods: `log`, `info`, `warn`, and `error`. These methods display different types of messages in the console.
#### Program 2: Grouping Messages ```html <script>"User Details"); console.log("Name: John Doe"); console.log("Age: 30"); console.log("Occupation: Web Developer"); console.groupEnd(); </script> ``` **Description:** This program uses `` and `console.groupEnd()` to group related messages, making the console output more organized.

Running the Programs 1. To run these programs, simply insert each script block into the HTML of a webpage. 2. Open the webpage in a Chromium-based browser. 3. Open the Developer Tools (usually F12 or right-click -> Inspect). 4. Navigate to the Console tab to see the output of these scripts.
Each of these programs provides a practical demonstration of how the console can be used for debugging and inspecting web pages in Chromium browsers.

JavaScript in HTML Example: Image Toggle

In this simple example, I will demonstrate how to use JavaScript within an HTML document to toggle an image back and forth between two different images when clicked.

This code illustrates best practices by using `let` and `const`.

We inline JavaScript to the `<script>` tag for better separation of concerns.

```html <!DOCTYPE html> <html> <head> <title>Image Toggle Example</title> <script> function toggleImage() { const img = document.getElementById('toggleImage'); if (img.src.endsWith('image1.jpg')) { img.src = 'image2.jpg'; } else { img.src = 'image1.jpg'; } } </script> </head> <body> <img id="toggleImage" src="image1.jpg" onclick="toggleImage()" style="cursor: pointer;" /> </body> </html> ```
Best practices:
1. The `img` variable is declared using `const` as it doesn't get reassigned a new value.
2. **Enhanced Readability**: The JavaScript function `toggleImage()` is kept in the `<script>` section of the HTML head, promoting cleaner code separation. This approach enhances readability and maintenance of the code.
3. **Use of `const` for `img`**: Since the `img` object reference doesn't change, `const` is more appropriate than `let`.
This updated version adheres to modern JavaScript practices, ensuring better maintainability and readability.

Lecture: Using Node.js in Visual Studio Code with JavaScript Concepts

#### Introduction

Welcome, everyone! Today, we are going to explore using Node.js in Visual Studio Code (VS Code) and dive into some fundamental JavaScript concepts like loops, switch-case, and if-then statements. Node.js allows us to run JavaScript outside the browser, and VS Code is an excellent IDE for JavaScript development.
#### Setting Up Node.js in VS Code
1. **Install Node.js:** - First, ensure that Node.js is installed on your system. You can download it from [](
2. **Setting Up VS Code:** - Install Visual Studio Code from []( - Open VS Code, and you can write JavaScript code directly in a new file. - Save the file with a `.js` extension, like `example.js`.
3. **Running JavaScript in VS Code:** - You can run your JavaScript file using Node.js right from the VS Code terminal. - Open the terminal in VS Code (`Terminal -> New Terminal`) and type `node example.js`.
#### JavaScript Program Demonstration
Now, let's create a simple program that demonstrates loops, switch-case, and if-then statements in JavaScript.
**example.js:** ```javascript // Loop: Print numbers from 1 to 5 console.log("Loop Output:"); for (let i = 1; i <= 5; i++) { console.log(i); }
// Switch-case: Assign a fruit name based on a number let number = 3; let fruit;
switch (number) { case 1: fruit = "Apple"; break; case 2: fruit = "Banana"; break; case 3: fruit = "Cherry"; break; default: fruit = "Unknown"; }
console.log("\nSwitch-Case Output:"); console.log("Fruit for number 3 is: " + fruit);
// If-then: Check if the number is greater than 2 console.log("\nIf-Then Output:"); if (number > 2) { console.log("The number is greater than 2."); } else { console.log("The number is not greater than 2."); } ```
Design Best Practices
1. **For Loop:** - Iterates from 1 to 5 and prints each number. Loops are used for executing a block of code multiple times.
2. **Switch-Case:** - Evaluates a variable (`number`) and executes different code blocks based on its value. It's an efficient alternative to multiple `if-else` statements.
3. **If-Then Statement:** - A basic conditional statement that performs different actions based on whether a condition is true or false.
Best Practices applications: Using Node.js with Visual Studio Code provides a powerful environment for developing and running JavaScript applications. The concepts we covered today - loops, switch-case, and if-then statements - are fundamental to JavaScript programming and form the basis for more complex logic and functionalities in applications.
#### Practice Exercise Try modifying the `example.js` file to include while loop, and experiment with the switch-case and if-then statements to familiarize yourself with their syntax and use cases.
In our next sessions, we will explore more advanced Node.js features and dive into asynchronous programming, handling HTTP requests, and building a basic Node.js application. Stay tuned and keep practicing!

Manipulating the Browser Object Model (BOM) in Chromium

Below is an example of JavaScript code designed to run in a Chromium-based browser. This script demonstrates how to create, delete, and manipulate DOM elements within the Browser Object Model (BOM), following ECMAScript 6 best practices.
This version demonstrates `addEventListener` to attach event listeners to the buttons.
```html <!DOCTYPE html> <html> <head> <title>BOM Manipulation Example</title> </head> <body> <button id="resizeWindowBtn">Resize Window</button> <button id="moveWindowBtn">Move Window</button> <button id="triggerAlertBtn">Trigger Alert</button> <button id="triggerPromptBtn">Trigger Prompt</button> <script> document.addEventListener('DOMContentLoaded', () => { // Resizing the window document.getElementById('resizeWindowBtn').addEventListener('click', () => { window.resizeTo(600, 400); // Resize the window to 600x400 pixels });
// Moving the window document.getElementById('moveWindowBtn').addEventListener('click', () => { window.moveTo(100, 100); // Move the window to coordinates (100, 100) });
// Triggering an alert document.getElementById('triggerAlertBtn').addEventListener('click', () => { alert('This is an alert!'); });
// Triggering a prompt document.getElementById('triggerPromptBtn').addEventListener('click', () => { let userResponse = prompt('Enter your name:', 'Name'); if (userResponse) { alert('Hello, ' + userResponse); } }); }); </script> </body> </html> ```

Applicability of best practices:

1. **Event Listeners**: `addEventListener` methods.
2. **DOMContentLoaded**: The script waits for the `DOMContentLoaded` event, ensuring that the DOM is fully loaded before attaching event listeners.
3. **Element Selection**: Uses `document.getElementById` to select each button and attach the corresponding event listener.
4. **Anonymous Functions**: Utilizes arrow functions for event handlers, following ES6 syntax.
This code adheres to modern JavaScript best practices, providing a cleaner and more modular approach to handling events. It also demonstrates how to interact with the BOM in a way that aligns with contemporary coding standards.

Case study of HTML and JavaScript code, adhering to ECMAScript best practices. This illustrates `addEventListener` to attach event listeners to the buttons and organizes the JavaScript code to enhance readability and maintainability.

```html <!DOCTYPE html> <html> <head> <title>DOM Manipulation Example</title> <style> .changedBackground { background-color: lightblue; }
.changedFont { font-family: Arial, sans-serif; color: green; }
.changedBorder { border: 2px solid red; padding: 10px; } </style> </head> <body> <h1 id="header">Hello, World!</h1> <p id="paragraph">This is a paragraph.</p> <div id="contentBox">Content Box</div>
<button id="backgroundButton">Change Background</button> <button id="fontButton">Change Font Style</button> <button id="borderButton">Change Border</button>
<script> document.addEventListener('DOMContentLoaded', () => { const header = document.getElementById('header'); const paragraph = document.getElementById('paragraph'); const contentBox = document.getElementById('contentBox');
document.getElementById('backgroundButton').addEventListener('click', () => { header.classList.toggle('changedBackground'); });
document.getElementById('fontButton').addEventListener('click', () => { paragraph.classList.toggle('changedFont'); });
document.getElementById('borderButton').addEventListener('click', () => { contentBox.classList.toggle('changedBorder'); }); }); </script> </body> </html> ```

ECMAScript 6 Best Practices:

1. Application of IDs to Buttons**: Each button has a unique ID for easier referencing in JavaScript.
2. Demonstrate `addEventListener`: JavaScript event listeners are attached using `addEventListener` for each button to handle click events.
4. **Organize the JavaScript Code**: The script waits for the `DOMContentLoaded` event to ensure the DOM is fully loaded before attaching event listeners. This is a good practice to prevent JavaScript from attempting to interact with elements that have not yet been loaded.
5. **Variable Declaration for DOM Elements**: Declaring variables (`header`, `paragraph`, `contentBox`) for the DOM elements at the top of the script provides a clear overview of the elements being manipulated and makes the code more readable.
By following these ECMAScript best practices, the code is cleaner, more modular, and aligns with contemporary standards in web development.
This approach achieves our goal of maintainability and paves the way for easier debugging and future code modifications.

Programmatically Creating, Changing, and Deleting HTML DOM Elements

This JavaScript example demonstrates how to programmatically create, modify, and delete HTML DOM elements.
This example can be embedded into an HTML file and run in a web browser.
ECMAScript 6 Best Practices Certified HTML and JavaScript code.
Herer we illustrate the use of `addEventListener` for attaching event listeners to the buttons, and organize the JavaScript code for better readability and maintainability.
```html <!DOCTYPE html> <html> <head> <title>DOM Manipulation Example</title> </head> <body> <div id="container"> <h1>JavaScript DOM Manipulation</h1> </div>
<button id="addElementBtn">Add Element</button> <button id="modifyElementBtn">Modify Element</button> <button id="deleteElementBtn">Delete Element</button>
<script> document.addEventListener('DOMContentLoaded', () => { const container = document.getElementById('container');
// Function to programmatically add an element document.getElementById('addElementBtn').addEventListener('click', () => { const newPara = document.createElement("p"); = "newElement"; newPara.textContent = "This is a new paragraph element!"; container.appendChild(newPara); });
// Function to modify the newly added element document.getElementById('modifyElementBtn').addEventListener('click', () => { const existingElement = document.getElementById("newElement"); if (existingElement) { existingElement.textContent = "This paragraph has been modified!"; = "blue"; } });
// Function to delete the added element document.getElementById('deleteElementBtn').addEventListener('click', () => { const existingElement = document.getElementById("newElement"); if (existingElement) { existingElement.remove(); } }); }); </script> </body> </html> ```
ECMAScript 6 Best Practices:
1. Apply IDs to Buttons**: Each button has a unique ID for easier referencing in JavaScript.
2. Apply `addEventListener`**: JavaScript event listeners are attached using `addEventListener` for each button to handle click events.
3. DOMContentLoaded Event: The script waits for the `DOMContentLoaded` event to ensure the DOM is fully loaded before attaching event listeners. This is a good practice to prevent JavaScript from attempting to interact with elements that have not yet been loaded.
5. **Organized JavaScript Code**: Declaring variables (`container`) for the DOM elements at the top of the script provides a clear overview of the elements being manipulated and makes the code more readable. The functions for adding, modifying, and deleting elements are defined within the scope of the event listeners, making the code modular and easier to manage.

Illustrating the applications of ECMAScript 6 Best Practices:

1. HTML Setup: - The div with the id `container` and three buttons are set up in the body. Each button has a unique ID for JavaScript interaction.
2. Adding an Element (`addElementBtn` listener): - When the "Add Element" button is clicked, a new `<p>` element is created and appended to the `container` div. This demonstrates how to create and insert new elements into the DOM.
3. Modifying an Element (`modifyElementBtn` listener): - The "Modify Element" button's listener locates the paragraph by its `id` and modifies its text and style if it exists. This illustrates how to access and alter existing DOM elements.
4. Deleting an Element (`deleteElementBtn` listener): - The "Delete Element" button's listener finds the paragraph by its `id` and removes it from the DOM, showcasing how to remove elements from the page.
Running the code:
1. Copy the entire code snippet into a new HTML file. 2. Open the file in a web browser. 3. Interact with the buttons to add, modify, and delete the paragraph element.
This example illustrates ECMAScript 6 best practices, providing a clean, modular, and therefore maintainable and extensible approach to DOM manipulation. It enhances maintainability, paves the way for easier debugging, and aligns with contemporary standards in web development.
By leveraging `addEventListener` and organizing the JavaScript code effectively, this example demonstrates fundamental DOM manipulation techniques and showcases how to write JavaScript in a more structured and maintainable manner.
This approach is crucial for developing larger, more complex web applications where good coding practices significantly impact the ease of development and collaboration.

ECMAScript 6 Coding Best Practices:

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
) instead.