Share
Explore

Programming JavaScript on the Client-side

megaphone

September 11: JavaScript in the BOM

DOM Manipulation
Introduction to the DOM
Selecting a HTML element using document.querySelector
Manipulating the HTML element, for example:
Changing the text displayed in a p or heading element
Changing the color and background color of a p or heading element
Inserting html using the document.innerHTML property


1
Session 6
TUE
SEPT 10
Client Side Scripting Setup
Overview of client-side scripting
Adding a external Javascript file to a webpage (app.js)
Executing the code in an app.js file after HTML content loads
The Programming Language of Javascript Syntax
Declaring variables with let and const
Conditionals with if and else
C-style loop
Arrow function
2

3
There are no rows in this table

Session 7: September 11

megaphone

DOM Manipulation

Introduction to the DOM
Selecting a HTML element using document.querySelector
Manipulating the HTML element, for example:
Changing the text displayed in a p or heading element
Changing the color and background color of a p or heading element
Inserting html using the document.innerHTML property

megaphone

Setting up for the JavaScript Lab Exercises:


We will program JavaScript on the “client” side <Chrome Browser to do our client JS programming”

Let’s now install node.exe so we can then use VSC to program JavaScript “on the Server side”

Student Lab Learning Workbook for Full Stack Web Application Development

Client-Side Scripting Setup

The Genesis of JavaScript:
History and Origin of JavaScript:
Introduction to JavaScript's roots as "Lucifer," a language for cable TV set-top box control.
Discuss the evolution of JavaScript into a web scripting language.
megaphone

### History and Origin of JavaScript:

pfeq:

JavaScript, originally conceived in the mid-1990s, has a fascinating history that intertwines both business and technological demands, reflecting its evolution in response to the rapidly changing digital landscape.
#### Early Roots as "Mocha" and "Lucifer": In its initial stages, JavaScript's roots were quite different from its modern form. The technology that would become JavaScript was first conceptualized as part of an effort to create an easy-to-use scripting language for cable TV set-top boxes.

It was internally code-named **"Mocha"** and later **"Lucifer"** by its inventor Brendan Eich, who was working at Netscape Communications at the time.

The original idea was to provide users of early set-top box systems with the ability to interact with their devices using a simple, lightweight programming language. This would allow viewers to access interactive television services and customize their experience, addressing early consumer demand for more control and interactivity in digital entertainment systems.
However, this project never took off for the set-top box market, primarily due to technical limitations and a lack of widespread consumer adoption of interactive television technology at the time. Despite this, the concept of a lightweight scripting language persisted and found new life in the rapidly growing internet era.

#### Business and Technology Drivers Leading to JavaScript's Evolution:

The mid-1990s was a period of explosive growth for the web, with millions of users beginning to browse websites for information and services. Netscape, the company behind the dominant web browser of the time, **Netscape Navigator**, recognized the need for a scripting language that could enhance the user experience beyond static HTML pages. Their business motivation was clear: make web pages more interactive to improve user engagement, drive adoption of their browser, and differentiate themselves from competitors like Microsoft's Internet Explorer.
This business-driven demand aligned with key technology trends:
1. **Rise of Dynamic Content**: The web was transitioning from static pages to interactive and dynamic content. Companies wanted to build web pages that responded to user actions, updated content without refreshing the page, and integrated multimedia elements.
2. **Lightweight, Accessible Programming**: The web was becoming increasingly democratized, with people from non-technical backgrounds wanting to build websites. Netscape needed a scripting language that was easy to learn and could be embedded directly into HTML pages, allowing both developers and hobbyists to create interactive web experiences.
3. **Cross-Platform Necessity**: With the growing number of operating systems (Windows, Mac, Unix), a key technical requirement for any new web technology was cross-platform compatibility. The scripting language needed to work universally across devices and platforms without additional configurations.

#### The Evolution into a Web Scripting Language:

In response to these technological drivers, Netscape commissioned Brendan Eich to develop a prototype for a browser-based scripting language. Initially known as **Mocha**, the language quickly evolved into **JavaScript** (a marketing-driven name designed to associate it with the growing popularity of Sun Microsystems' Java language, despite the two being very different).
Eich’s main goal was to create a scripting language that non-programmers and web designers could easily use to make their web pages more interactive. JavaScript was designed to be **lightweight, interpreted (not compiled)**, and **event-driven**, enabling quick iterations and responsive page updates based on user interaction.
In 1995, JavaScript made its debut in Netscape Navigator 2.0, marking the beginning of its rapid adoption. Its ability to handle form validations, respond to mouse events, and dynamically change HTML content made it a perfect fit for web development needs.
#### Consumer Demand and the Browser Wars: As the web became central to both business and consumer life, demand for richer, more responsive user experiences skyrocketed. The period of the **"Browser Wars"** in the late 1990s, where Netscape and Microsoft were in fierce competition for browser dominance, further accelerated the adoption of JavaScript.
Microsoft, recognizing the importance of dynamic scripting, reverse-engineered JavaScript and implemented its own version, called **JScript**, for Internet Explorer. This further solidified JavaScript as a web standard. Eventually, both companies recognized the need for standardization, leading to JavaScript being submitted to the **ECMA International** organization for formalization as **ECMAScript** in 1997, ensuring consistent behavior across different browsers and platforms.
#### Consumer Demand for JavaScript-Driven Interactivity: The rapid adoption of the internet as a major communication and commercial platform drove **consumer demand for interactive web applications**. Users wanted more responsive sites that could load content dynamically without full page reloads—something JavaScript enabled. Early use cases like: - Real-time form validation - Interactive image rollovers - Dropdown menus - Pop-up windows
...became staples of the early web, making browsing more engaging and efficient for users. As businesses adopted e-commerce, online services, and richer multimedia content, JavaScript’s role in improving user experience became critical.

The Modern Era and the Emergence of Web 2.0:
Over time, JavaScript's role expanded significantly. The **AJAX revolution** of the mid-2000s was pivotal, enabling asynchronous web applications that could update parts of a web page without needing to reload the entire page. This met the consumer demand for faster, more fluid interactions and enabled the rise of **Web 2.0**—a more social, dynamic, and participatory web environment.
Today, JavaScript is a cornerstone technology of the modern web. It powers everything from basic webpage interactivity to full-fledged applications like Google Maps, Twitter, and Facebook. It has evolved far beyond its initial intent, now enabling developers to build robust, scalable web applications both on the client (browser) and server (Node.js) sides.
#### Conclusion: JavaScript's origins as a tool for interactive television set-top boxes may have been short-lived, but the fundamental ideas it embodied—accessibility, interactivity, and cross-platform compatibility—were key to its transformation into the web’s most ubiquitous scripting language.

Driven by business needs for browser differentiation and technological advances in dynamic content, JavaScript’s evolution mirrored the broader shift of consumer demand toward richer, more responsive, and engaging web experiences.

Today, JavaScript is indispensable in web development, serving as a core enabler of modern digital life.
Chromium V8 and JavaScript Interpretation:
Explain the role of Chromium V8 as a high-performance JavaScript engine.
Briefly touch on just-in-time (JIT) compilation and its impact on JavaScript execution.
info

### Chromium V8 and JavaScript Interpretation:

In the world of JavaScript execution, the development of high-performance engines was a critical factor in driving the rapid growth and efficiency of web applications. One of the most important milestones in this evolution was the creation of **Chromium V8**, a JavaScript engine that revolutionized how browsers handled JavaScript, allowing for significantly faster execution times and more complex web applications.
#### The Role of Chromium V8 as a High-Performance JavaScript Engine: Chromium V8, developed by **Google** in 2008, is an open-source JavaScript engine designed to increase the speed and efficiency of JavaScript execution within web browsers. At the time, the web was transitioning into a more dynamic, application-driven environment. Companies like Google were at the forefront of developing complex web-based applications, such as Gmail and Google Maps, which demanded far more processing power and responsiveness than early JavaScript engines could provide.
Before V8, JavaScript engines interpreted code line-by-line, often leading to significant performance bottlenecks, especially in applications requiring frequent interaction, data manipulation, or DOM updates. The slow performance of JavaScript engines was becoming a major issue as businesses and developers wanted to move beyond static web pages and offer more immersive, real-time experiences.
#### Key Objectives Behind V8’s Development: The primary motivation for creating V8 was to address these performance limitations and unlock JavaScript's full potential as a language for web applications. Google recognized that fast, efficient JavaScript execution was not only necessary to improve the performance of its own applications but also a crucial factor in enabling broader adoption of web-based technologies.
From a **business perspective**, Google was highly invested in the development of its Chrome browser as a means of enhancing its core business models, which relied on web-based services and applications. Faster JavaScript execution would lead to a smoother user experience, higher engagement with web services, and a growing preference for web-based over desktop applications.
#### V8’s Architecture and Optimization: V8 was designed from the ground up to be a high-performance JavaScript engine. It introduced several critical innovations that made it a game-changer:
1. **Efficient Memory Management**: V8 compiles JavaScript code directly into **native machine code** before execution, rather than interpreting it in real-time. This not only reduces the overhead of interpreting JavaScript but also allows the engine to handle memory more efficiently, ensuring faster execution and better garbage collection. 2. **High Performance Across Platforms**: Unlike older engines, which were often tied to specific platforms or browsers, V8 was designed to be fast on any system. By translating JavaScript into machine code that the CPU could execute directly, V8 dramatically reduced the amount of time it took to run JavaScript-heavy applications.
3. **Scalability for Large Applications**: Google’s aim was to build large, complex, and scalable web applications using JavaScript. V8 was built to handle applications that required significant computational power, enabling modern web apps like Google Maps, which require heavy computation for rendering maps, routing, and delivering real-time data.
By combining these techniques, V8 allowed Chrome to deliver a **smoother, faster browsing experience**, which in turn supported Google’s goal of growing its ecosystem of web services and applications. V8's success had ripple effects throughout the web development world, raising user expectations for fast, seamless web applications.
#### Just-In-Time (JIT) Compilation and Its Impact on JavaScript Execution: One of the most significant technological innovations that Chromium V8 brought to JavaScript was **Just-In-Time (JIT) compilation**. JIT compilation is a technique used by V8 to optimize the performance of JavaScript code dynamically during runtime. Here’s how it works:
1. **Initial Compilation**: When JavaScript code is first loaded by the browser, V8 compiles it into **intermediate machine code** that the CPU can execute, skipping the traditional interpretation step. 2. **Dynamic Optimization**: During runtime, V8 monitors how the JavaScript code is being used. Based on usage patterns (e.g., how often certain functions are called or how certain variables are used), the engine **recompiles and optimizes** the code on-the-fly. This ensures that frequently used functions or operations are executed more efficiently over time. 3. **De-Optimization**: V8 can also undo optimizations when it detects that assumptions about how the code is used have changed. This flexibility ensures that the engine adapts to different workloads while maintaining performance.
The introduction of JIT compilation was revolutionary because it allowed JavaScript engines to achieve **both speed and flexibility**. In the past, JavaScript had been criticized for being slow compared to languages like C++ or Java, but JIT allowed V8 to dynamically optimize code execution in real-time, making JavaScript much more competitive.
#### Impact on Business and Consumer Experiences: JIT compilation, as implemented in V8, had a profound impact on the web development ecosystem:
1. **Faster Load Times and Interaction**: With JIT, web applications could execute JavaScript code faster, leading to shorter load times and more responsive interactions. This was especially important for businesses developing rich, interactive applications where user engagement was directly tied to performance.
2. **Enabling Rich Web Applications**: Complex web applications that were previously impractical due to performance constraints—such as online gaming, 3D rendering in the browser, and large-scale data processing—became possible. Google’s own products, like Google Docs and Google Sheets, rely heavily on JavaScript and are prime examples of the capabilities unlocked by V8 and JIT compilation.
3. **Cost Efficiency for Businesses**: Businesses investing in web technologies saw tangible benefits. Applications powered by high-performance JavaScript engines like V8 could reach larger audiences without the need for platform-specific software. This **cross-platform capability** drastically reduced development costs while allowing businesses to deliver the same high-quality experiences on various devices, from desktops to mobile phones.
4. **Rise of Single-Page Applications (SPAs)**: V8’s performance improvements were pivotal in the rise of **Single-Page Applications (SPAs)**, where large amounts of JavaScript run in the browser to create a smooth, desktop-like experience. Frameworks such as Angular, React, and Vue.js thrived because V8 could handle the complexity of client-side rendering and state management with minimal performance penalties.
#### Conclusion: Chromium V8 transformed JavaScript from a sluggish, interpreted scripting language into a fast, highly optimized environment capable of running large-scale applications. By implementing advanced techniques like JIT compilation and focusing on high-performance execution, V8 played a critical role in reshaping the web, allowing businesses to build faster, more complex, and more user-friendly web applications.
The business case behind V8 was clear: improve web performance to fuel the growth of web applications, increase user engagement, and support business models based on web services. Today, V8 remains a foundational component of not only Google Chrome but also **Node.js**, powering JavaScript applications on the server side and ensuring JavaScript’s place as one of the most important programming languages in the world.
ECMA Script Specification and Open Source Advantages:
Introduce the ECMA (European Computer Manufacturers Association) Script specification as the governing standard for JavaScript.
Highlight the benefits of JavaScript being free and open source, fostering community-driven development and innovation.
megaphone

### ECMA Script Specification and Open Source Advantages

JavaScript, as we know it today, owes much of its consistency, growth, and global adoption to two pivotal factors: the **ECMA Script specification** and the fact that it is **free and open source**. These elements have played a crucial role in shaping the language into a highly standardized, yet innovative and evolving ecosystem, driven by both industry and community contributions.
#### The ECMA (European Computer Manufacturers Association) Script Specification: JavaScript, created by **Brendan Eich** at Netscape in 1995, became popular quickly. However, early on, there were issues of **compatibility** between different browsers, particularly during the **"Browser Wars"** of the late 1990s, when both Netscape Navigator and Microsoft Internet Explorer were competing for market dominance. Each browser had its own slightly different implementation of JavaScript, leading to inconsistencies in how web pages behaved across platforms.
To address this fragmentation, **Netscape** submitted JavaScript to the **European Computer Manufacturers Association (ECMA)** in 1996 to create a formalized specification for the language. ECMA is an international standards organization that specializes in information and communication technology standards. The result was **ECMA-262**, the first specification of **ECMAScript**, published in 1997.
##### What is ECMAScript? ECMAScript is the official standard that defines the core features of JavaScript. While "JavaScript" is a trademark owned by **Oracle**, "ECMAScript" refers to the standardized specification of the language. The term **ECMAScript** is essentially a blueprint for JavaScript and other JavaScript-like languages (e.g., JScript and ActionScript). All modern JavaScript engines—like Google's V8, Mozilla's SpiderMonkey, and Microsoft's Chakra—implement ECMAScript specifications, ensuring uniformity across platforms.
##### The Evolution of ECMAScript: The ECMAScript specification is continually updated to reflect new developments in JavaScript. Over the years, the standards body, **ECMA TC39 (Technical Committee 39)**, has played a pivotal role in guiding the language’s evolution, ensuring it remains stable, consistent, and compatible across all environments.
- **ES3 (1999)**: Included significant improvements, fixing early inconsistencies in the language. - **ES5 (2009)**: Introduced features like strict mode, JSON support, and better object manipulation methods. - **ES6/ES2015 (2015)**: The most substantial update, bringing features such as arrow functions, classes, modules, promises, and let/const variable declarations. ES6 marked the beginning of yearly updates to the language. - **Modern ECMAScript Updates (ES2016+)**: Continued incremental improvements, adding async/await, generators, and more sophisticated capabilities.
The **ECMA standard** ensures that new features and language improvements are introduced in a systematic, backward-compatible way, allowing the global developer community to rely on a consistent, predictable JavaScript language.
##### Business Impact of Standardization: For businesses, the ECMA standard is crucial. It ensures that JavaScript applications work consistently across different browsers and platforms, reducing the cost and complexity of developing web applications. Standardization also fosters **interoperability**, which is essential for businesses targeting users across a variety of devices and environments. Companies can invest confidently in JavaScript development, knowing that the language is future-proof, widely supported, and will not fragment across different environments.
#### Open Source JavaScript: Fostering Community-Driven Development and Innovation
One of the key advantages of JavaScript is its **open-source** nature. Since its creation, JavaScript has been freely available to developers around the world. Both the language itself and the tools built around it (like JavaScript engines and frameworks) have benefited from the open-source ethos, leading to rapid growth, collaboration, and innovation.
##### The Benefits of JavaScript Being Free and Open Source:
1. **Widespread Adoption**: JavaScript's **free** availability significantly contributed to its rapid adoption by developers, businesses, and browser makers. As the web grew in popularity, developers didn’t have to worry about licensing fees or restrictions when incorporating JavaScript into their projects. This **lack of financial barriers** allowed a diverse range of developers—from hobbyists to large corporations—to experiment with and adopt the language.
2. **Community-Driven Development**: One of the greatest strengths of open-source projects is that they harness the power of the global developer community. This applies directly to JavaScript, which has seen its ecosystem flourish due to **community contributions**. Developers around the world contribute to the development of JavaScript engines, libraries, and frameworks. Popular projects like **Node.js**, **React**, **Vue.js**, and **jQuery** emerged from the open-source community, offering tools and solutions that drive web development innovation.
Additionally, **TC39**, the committee responsible for advancing the ECMAScript specification, is made up of not just companies like Google, Microsoft, and Mozilla, but also independent developers and contributors. This ensures that the language evolves with the needs of the community, reflecting real-world usage and challenges.
3. **Rapid Innovation**: The open-source nature of JavaScript has fostered rapid innovation in web development. Anyone can propose new libraries, frameworks, or tools, and these innovations can be rapidly shared and adopted across the community. A great example is the **npm (Node Package Manager)** ecosystem, which contains over a million JavaScript libraries and packages that are open-source and readily available to developers.
This **ecosystem of free tools** has transformed JavaScript into one of the most versatile and widely-used programming languages. From frontend development with frameworks like React and Angular to backend solutions powered by Node.js, JavaScript has become essential across the entire software development stack.
4. **Cross-Platform and Device Versatility**: Because JavaScript is open source, it can be easily adapted and extended to work in a variety of environments. Today, JavaScript runs **everywhere**: in web browsers, on servers, and even on embedded systems or IoT devices. Projects like **Node.js** allow JavaScript to run on the server side, while **Electron** enables developers to build cross-platform desktop applications. This adaptability has been a critical driver of JavaScript’s dominance.
5. **Lowering Development Costs**: Open-source JavaScript and the libraries built around it significantly lower the cost of web development. Companies don’t need to pay for proprietary tools or languages when building rich web applications. Moreover, the vast ecosystem of pre-built libraries, frameworks, and tools means developers can often **reuse existing code**, reducing development time and costs.
##### Business and Technological Impact of Open Source JavaScript: - **Faster Time-to-Market**: Businesses can build applications faster using JavaScript due to the wide availability of **open-source libraries** and tools. This reduces the need to reinvent the wheel and accelerates innovation cycles. - **Lower Costs**: With no licensing fees or restrictive software costs, businesses can adopt JavaScript freely across their projects, lowering overall development costs. This has been a key driver for startups and enterprises alike. - **Access to Talent**: The open-source nature of JavaScript has cultivated a large, active community of developers. For businesses, this means access to a vast talent pool of developers skilled in JavaScript, which remains one of the most popular programming languages in the world. - **Innovation and Flexibility**: The open-source ethos fosters an environment of experimentation and collaboration, which leads to cutting-edge frameworks and tools. Businesses benefit from **community-driven innovation**, using these tools to stay competitive and agile.
#### Conclusion: The **ECMA Script specification** and **open-source nature** of JavaScript have been fundamental in driving the language’s widespread adoption and rapid evolution. Standardization through ECMA ensures cross-browser compatibility and stability, giving businesses and developers confidence in their investment in JavaScript-based technologies. At the same time, its open-source foundation has allowed the community to drive innovation, creating an ecosystem of tools, libraries, and frameworks that power everything from small websites to large-scale enterprise applications. This combination of **open innovation** and **consistent standards** has made JavaScript the backbone of modern web development.
JavaScript's Integration into Web Browsers and Node.js:
Discuss Marc Andreessen's adoption of JavaScript into Netscape Navigator for dynamic web page manipulation.
Explain Ryan Dahl's creation of Node.js, enabling JavaScript execution outside of web browsers (server-side scripting).
Running JavaScript in the Browser and Node.js:
NODE.js is a wrapper around Chromium which the JavaScript Language Interpeter
With Node.js - you can run JavaScript as an Operating System Process, at the command line, “Server Side JavaScript”
Chrome can run JS in HTML pages because browsers have a Chromium JavaScript Interpeter.
Contrast executing JavaScript in the browser's environment (Browser Object Model or BOM) with running it in the Node.js shell (Console object model).
JavaScript Code Drills Outline:
Present a structured outline of 10 JavaScript coding exercises, starting from basic variable declarations (let, var, const) and progressing to more advanced concepts like objects and TypeScript.
Installing Node.js for Command-Line JavaScript:
Provide step-by-step instructions on installing Node.js to enable running JavaScript from the command line.

Lab Exercises:

Overview of client-side scripting: CLIENT → Web Browser
(The other way is “Server-side” which means Node.js, JS as an OS process).
Explain the fundamental concept of client-side scripting and its role in enhancing web page interactivity.
Adding an external JavaScript file to a webpage (app.js):
Guide students on how to include an external JavaScript file (app.js) within an HTML document.
Executing the code in an app.js file after HTML content loads:
Demonstrate how to ensure JavaScript code execution occurs after the HTML content has fully loaded, using techniques like event listeners or script placement.

JavaScript Syntax

Lab Exercises A:
megaphone

Student Activity 1: Add the numbers 1 to 100 and output the sum


let startNumber = 1;
let sum = 0;
let endNumber = 100;
let currentNumber =startNumber;
for ( ; currentNumber <= 100; ){
sum += currentNumber++
}
console.log(sum); // Output: 5050

Student Activity 2: Take the above and wrap up the core logic into a FUNCTION

function a(startNumber, endNumber){
let sum = 0;
let currentNumber =startNumber;
for ( ; currentNumber <= endNumber; ){
sum += currentNumber++
}
return(sum);
}

let answer = a(1, 100)
console.log(answer);

Student Activity 3: Do this with Classes and OBJECTS:

In JavaScript, you can encapsulate logic like the "add numbers from 1 to 100" algorithm inside a **class** to make it reusable and modular.
A class in JavaScript is a blueprint for creating objects.
Let’s encapsulate the addition logic inside a class called `NumberAdder`.
### **Steps to Encapsulate the Logic in a Class:**
1. **Create a Class**: We'll create a class `NumberAdder` that will contain the logic for adding numbers. 2. **Create Methods**: The class will have a method `calculateSum` that performs the addition. 3. **Instantiate the Class**: We'll create an instance of the `NumberAdder` class and use it to calculate the sum.
### **Example:**
```javascript // Define the class NumberAdder class NumberAdder { // Constructor to initialize the start and end numbers constructor(startNumber, endNumber) { this.startNumber = startNumber; this.endNumber = endNumber; this.sum = 0; // This will store the sum }
// Method to calculate the sum from startNumber to endNumber calculateSum() { let currentNumber = this.startNumber; // Loop through numbers and add them to sum while (currentNumber <= this.endNumber) { this.sum += currentNumber++; }
// Return the calculated sum return this.sum; }
// Method to reset the sum if needed reset() { this.sum = 0; } }
// Using the class and object
// Create an object of the NumberAdder class for numbers 1 to 100 const adder = new NumberAdder(1, 100);
// Call the calculateSum method const sum = adder.calculateSum();
// Output the result console.log("Sum of numbers 1 to 100:", sum); // Output: 5050
// Optionally reset the sum and recalculate adder.reset(); const newSum = adder.calculateSum(); console.log("Sum after reset:", newSum); // Output: 5050 ```
### **Explanation:**
1. **Class Definition**: - We define a class `NumberAdder` with a **constructor** that initializes the starting and ending numbers and a `sum` variable. 2. **Method `calculateSum()`**: - This method performs the addition using a `while` loop. It starts from `this.startNumber` and continues until it reaches `this.endNumber`. The `sum` is accumulated in `this.sum` and returned. 3. **Method `reset()`**: - This method resets the sum to `0`. It's useful if you want to reuse the object for a new sum calculation. 4. **Using the Object**: - We create an object `adder` by calling `new NumberAdder(1, 100)`. This object is used to call the `calculateSum()` method, which calculates the sum from 1 to 100. - The result is logged to the console using `console.log()`.
### **Benefits of Using Classes and Objects:** - **Modularity**: The logic for adding numbers is encapsulated in a class, making the code cleaner and reusable. - **Reusability**: You can create multiple instances of `NumberAdder` for different ranges of numbers. - **Maintainability**: Methods like `calculateSum()` and `reset()` make the code more flexible and easier to maintain or extend in the future.
### **Example of Using Multiple Objects**:
You can easily create multiple instances of the `NumberAdder` class to sum different ranges of numbers:
```javascript // Create an object to add numbers from 1 to 50 const adder1 = new NumberAdder(1, 50); console.log("Sum of numbers 1 to 50:", adder1.calculateSum()); // Output: 1275
// Create another object to add numbers from 51 to 100 const adder2 = new NumberAdder(51, 100); console.log("Sum of numbers 51 to 100:", adder2.calculateSum()); // Output: 3775 ```
This flexibility allows you to handle different ranges or reset and reuse the object as needed.


Declaring variables with let and const:
Provide hands-on practice in declaring variables using let (for mutable values) and const (for immutable values).
Conditionals with if and else:
Implement conditional logic using if, else if, and else statements to control program flow based on specific conditions.
C-style loop:
Introduce the traditional for loop (C-style loop) for iterative execution of code blocks.
Arrow function:
Explain the concise syntax and benefits of arrow functions for defining functions.
error

Here are JavaScript code exercises to help students understand and practice JavaScript syntax, focusing on variable declaration, conditionals, loops, and arrow functions:

### 1. Declaring Variables with `let` and `const`
#### Explanation: - `let`: Used to declare variables whose values **can be changed**. It has block scope, meaning the variable only exists within the block where it's declared. - `const`: Used to declare variables whose values **cannot be changed** once assigned. It also has block scope.
#### Exercise:
1. **Declare variables using `let` for mutable values**. 2. **Declare variables using `const` for immutable values**. 3. **Attempt to reassign a `const` variable and observe the error**.
#### Code Example: ```javascript // 1. Declare a variable with `let` and change its value let age = 25; console.log("Initial age:", age); // Output: 25
age = 26; console.log("Updated age:", age); // Output: 26
// 2. Declare a constant variable with `const` and try to reassign it const birthYear = 1998; console.log("Birth Year:", birthYear); // Output: 1998
// Uncommenting the next line will throw an error // birthYear = 2000; // Error: Assignment to constant variable
// 3. Experimenting with scope of `let` if (true) { let scopedVariable = "I exist only in this block"; console.log(scopedVariable); // Output: I exist only in this block }
// console.log(scopedVariable); // Error: scopedVariable is not defined
// 4. Using `const` for objects - you can modify object properties, but not reassign the object const person = { name: "Alice", age: 30 }; console.log(person); // Output: { name: 'Alice', age: 30 }
person.age = 31; // Allowed: Modifying property console.log(person); // Output: { name: 'Alice', age: 31 }
// person = { name: "Bob", age: 25 }; // Error: Assignment to constant variable ```
#### Key Points: - `let` is for values that may change. - `const` is for values that stay constant (with the exception of modifying properties of objects/arrays). - Variables declared with `let` and `const` are **block-scoped**.
---
### 2. Conditionals with `if` and `else`
#### Explanation: - Conditional statements control the flow of the program based on specific conditions. Use `if` to execute code when a condition is true, `else if` for an additional condition, and `else` for fallback code when no conditions are true.
#### Exercise:
1. Write an `if` statement that checks if a number is positive, negative, or zero. 2. Use `else if` to handle different conditions. 3. Implement a fallback with `else`.
#### Code Example: ```javascript let number = -10;
// 1. Check if the number is positive if (number > 0) { console.log("The number is positive."); } // 2. Check if the number is negative else if (number < 0) { console.log("The number is negative."); } // 3. Handle the case where the number is zero else { console.log("The number is zero."); }
// Try changing the number value to 10 or 0 and observe the output ```
#### Additional Exercise:
1. Create a grading system using `if-else` statements: - 90-100: A - 80-89: B - 70-79: C - 60-69: D - Below 60: F
```javascript let score = 85;
if (score >= 90) { console.log("Grade: A"); } else if (score >= 80) { console.log("Grade: B"); } else if (score >= 70) { console.log("Grade: C"); } else if (score >= 60) { console.log("Grade: D"); } else { console.log("Grade: F"); } ```
#### Key Points: - Use `if` to check conditions, `else if` for additional checks, and `else` for a fallback option. - The program executes the first `true` condition it encounters.
---
### 3. C-Style `for` Loop
#### Explanation: - The traditional `for` loop is a way to repeatedly execute a block of code a set number of times. It has three parts: initialization, condition, and iteration expression.
#### Exercise:
1. Write a `for` loop to print numbers from 1 to 10. 2. Modify the loop to print only even numbers between 1 and 10. 3. Use a loop to calculate the sum of numbers from 1 to 100.
#### Code Example:
```javascript // 1. Print numbers from 1 to 10 for (let i = 1; i <= 10; i++) { console.log(i); // Output: 1, 2, 3, ..., 10 }
// 2. Print even numbers from 1 to 10 for (let i = 1; i <= 10; i++) { if (i % 2 === 0) { console.log(i); // Output: 2, 4, 6, 8, 10 } }
// 3. Calculate the sum of numbers from 1 to 100 let sum = 0; for (let i = 1; i <= 100; i++) { sum += i; } console.log("Sum of numbers from 1 to 100:", sum); // Output: 5050 ```
#### Key Points: - The loop's structure: `for (initialization; condition; iteration)`. - The loop runs as long as the condition is `true`. - Update the loop variable (like `i++`) after each iteration.
---
### 4. Arrow Functions
#### Explanation: - Arrow functions provide a **concise syntax** for writing functions in JavaScript. - Unlike regular functions, arrow functions do not have their own `this` context, making them ideal for situations where you want to avoid binding issues (e.g., with callbacks).
#### Exercise:
1. Write an arrow function that takes two numbers and returns their sum. 2. Convert a traditional function to an arrow function. 3. Use an arrow function in an array's `map` method.
#### Code Example:
```javascript // 1. Arrow function to return the sum of two numbers const add = (a, b) => a + b; console.log(add(5, 10)); // Output: 15
// 2. Traditional function vs Arrow function // Traditional function function multiply(a, b) { return a * b; } console.log(multiply(4, 5)); // Output: 20
// Arrow function equivalent const multiplyArrow = (a, b) => a * b; console.log(multiplyArrow(4, 5)); // Output: 20
// 3. Use an arrow function with `map` to double the values in an array const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(num => num * 2); console.log(doubled); // Output: [2, 4, 6, 8, 10]
// 4. Arrow function with no parameters const greet = () => console.log("Hello, world!"); greet(); // Output: Hello, world! ```
#### Key Points: - Arrow functions offer a shorter syntax: `const funcName = (param1, param2) => { // function body };`. - For single-line functions, the `{}` and `return` can be omitted. - They are ideal for callbacks and array manipulation functions like `map`, `filter`, or `reduce`. - Arrow functions don't have their own `this`, which avoids `this` binding issues.
---
These exercises provide a strong foundation in understanding the syntax of JavaScript, covering variables, conditionals, loops, and functions. Practicing these will help students internalize these key language features.


megaphone

JavaScript in the BOM Browser

Here’s a simple HTML page with a basic calculator that allows you to enter two numbers and select an operation (addition, subtraction, multiplication, division) from a dropdown menu.

This is an example of using FORMS.

The result is displayed in a `<p>` element using JavaScript.
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Calculator</title> <style> body { font-family: Arial, sans-serif; padding: 20px; }
.container { max-width: 300px; margin: 0 auto; }
input, select, button { margin: 10px 0; padding: 8px; width: 100%; font-size: 1rem; }
button { background-color: #4CAF50; color: white; border: none; cursor: pointer; }
button:hover { background-color: #45a049; }
#answer { margin-top: 20px; font-size: 1.2rem; font-weight: bold; } </style> </head> <body>
<div class="container"> <h2>Simple Calculator</h2>
<!-- Number 1 Input Field --> <label for="num1">Enter First Number:</label> <input type="number" id="num1" placeholder="First number">
<!-- Number 2 Input Field --> <label for="num2">Enter Second Number:</label> <input type="number" id="num2" placeholder="Second number">
<!-- Dropdown for Operation Selection --> <label for="operation">Select Operation:</label> <select id="operation"> <option value="add">Add</option> <option value="subtract">Subtract</option> <option value="multiply">Multiply</option> <option value="divide">Divide</option> </select>
<!-- Button to Calculate --> <button onclick="calculate()">Calculate</button>
<!-- Output for Answer --> <p id="answer">Result will appear here...</p> </div>
<script> // Function to perform the calculation function calculate() { // Get the values from input fields const num1 = parseFloat(document.getElementById('num1').value); const num2 = parseFloat(document.getElementById('num2').value); const operation = document.getElementById('operation').value;
let result;
// Check if inputs are valid numbers if (isNaN(num1) || isNaN(num2)) { document.getElementById('answer').textContent = "Please enter valid numbers."; return; }
// Perform the selected operation if (operation === 'add') { result = num1 + num2; } else if (operation === 'subtract') { result = num1 - num2; } else if (operation === 'multiply') { result = num1 * num2; } else if (operation === 'divide') { if (num2 === 0) { document.getElementById('answer').textContent = "Cannot divide by zero!"; return; } result = num1 / num2; }
// Display the result in the paragraph element document.getElementById('answer').textContent = "Result: " + result; } </script>
</body> </html> ```
### Explanation: 1. **HTML Structure**: - We have two input fields (`<input type="number">`) for entering numbers. - A `<select>` dropdown is used to choose between addition, subtraction, multiplication, and division. - A button triggers the calculation by calling the `calculate()` function. - The result is displayed inside a `<p>` element with the id `answer`.
2. **CSS Styling**: - The styles are simple and centered for better readability. - Buttons and input fields are made responsive and styled for a cleaner look.
3. **JavaScript Functionality**: - The `calculate()` function gets the values from the two input fields and the operation dropdown. - Based on the selected operation, the corresponding arithmetic operation is performed. - If either input is invalid, or if division by zero occurs, appropriate messages are shown. - The result is dynamically updated in the `<p>` element with id `answer`.





Additional Considerations:
Incorporate interactive elements: Include quizzes, coding challenges, or interactive demos to reinforce learning.
Provide clear explanations and examples: Ensure that the content is accessible to students with varying levels of programming experience.
Offer opportunities for practice: Include ample exercises and projects for students to apply their knowledge.
Encourage experimentation: Create an environment where students feel comfortable exploring and trying new things.
info

Session 7 DOM Manipulation

Lesson Plan: **DOM Manipulation**
Introduction and Segue from JavaScript in the Browser and Node.js**
In our last lesson, we explored how JavaScript operates within both **browser environments** and **Node.js**.
We discussed how JavaScript interacts with the **Browser Object Model (BOM)** in the browser and how it serves as a robust backend technology in Node.js.
Now, we’ll focus on a crucial aspect of JavaScript in the browser: **DOM Manipulation**.

While Node.js enables JavaScript to operate on servers and handle data-intensive tasks, in the **browser**, JavaScript shines as the primary tool for making web pages interactive and dynamic.
This is achieved through the **Document Object Model (DOM)**, which represents the structure of an HTML document.

### **What is the DOM and BOM?**

The **DOM (Document Object Model)** is an interface that represents the HTML structure of a web page as a tree of objects, where each HTML element becomes a **node** in this tree.

The DOM allows JavaScript to **access, modify, and interact** with these HTML elements programmatically, enabling you to change the content, style, and structure of a web page dynamically without reloading it.

The **BOM (Browser Object Model)** refers to the various objects provided by the browser that allow JavaScript to interact with the browser window itself—managing things like alerts, window resizing, and navigation.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.