Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Web Programming Lab Manual 06 JavaScript (Advance) (1)

Uploaded by

jahidul.cse.gub
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Web Programming Lab Manual 06 JavaScript (Advance) (1)

Uploaded by

jahidul.cse.gub
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Department of

Computer Science and Engineering

Title: Introduction to JavaScript (JS) Advance

Web Programming Lab


CSE 302

Green University of Bangladesh


1 Objective(s)
• To gain knowledge of advanced JavaScript concepts.
• To learn about ES6+ features, asynchronous programming, closures, prototypes, JavaScript frameworks,
and the DOM (Document Object Model).

2 Problem analysis
The objective of this lab manual is to introduce students to advanced concepts in JavaScript that go beyond the
foundational knowledge of variables, functions, and events. These advanced concepts include ECMAScript 6
(ES6) features, asynchronous programming, closures, prototypes, JavaScript modules, and DOM manipulation.
The challenge is to provide a structured learning path that enables students to understand and practically apply
these advanced topics in real-world web development scenarios.
The manual also requires students to handle asynchronous tasks, interact with APIs, and manipulate the
Document Object Model (DOM) dynamically. These are essential skills for modern JavaScript development
but can be difficult for students transitioning from basic programming concepts.

3 Implementation of JavaScript ES6+ features, asynchronous pro-


gramming, closures, prototypes, JavaScript frameworks, and the
DOM
3.1 ES6+ Features in JavaScript
JavaScript has undergone many changes, with ECMAScript 6 (ES6) introducing several new features.

3.1.1 Arrow Functions

1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script>
7 const sum = (a, b) => a + b;
8 console.log(sum(5, 10)); // Output: 15
9 </script>
10
11 </body>
12
13 </html>

3.1.2 Template Literals

1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script>
7 const name = ’John’;
8 console.log(‘Hello, ${name}!‘); // Output: Hello, John!
9 </script>
10
11 </body>
12

© Dept. of Computer Science and Engineering, GUB


13 </html>

3.1.3 Default Parameters

1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script>
7 function greet(name = ’Guest’) {
8 return ‘Hello, ${name}‘;
9 }
10 console.log(greet()); // Output: Hello, Guest
11 console.log(greet(’Alice’)); // Output: Hello, Alice
12 </script>
13
14 </body>
15
16 </html>

3.1.4 Destructuring Assignment

1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script>
7 const [x, y] = [1, 2];
8 console.log(x, y); // Output: 1 2
9
10 const { name, age } = { name: ’John’, age: 30 };
11 console.log(name, age); // Output: John 30
12 </script>
13
14 </body>
15
16 </html>

3.2 Asynchronous JavaScript


3.2.1 Promises

1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script>
7 const promise = new Promise((resolve, reject) => {
8 let success = true; // Modify to test resolve/reject
9 if (success) {
10 resolve(’Operation successful’);
11 } else {
12 reject(’Operation failed’);

© Dept. of Computer Science and Engineering, GUB


13 }
14 });
15
16 promise
17 .then(message => console.log(message))
18 .catch(error => console.error(error));
19 </script>
20
21 </body>
22
23 </html>

3.2.2 Async/Await

1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script>
7 async function fetchData() {
8 try {
9 const response = await fetch(’https://jsonplaceholder.typicode.
com/posts/1’);
10 const data = await response.json();
11 console.log(data);
12 } catch (error) {
13 console.error(’Error:’, error);
14 }
15 }
16 fetchData();
17 </script>
18
19 </body>
20
21 </html>

3.2.3 Event Loop

1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script>
7 setTimeout(() => console.log(’Hello after 1 second’), 1000);
8 console.log(’This runs first’);
9 </script>
10
11 </body>
12
13 </html>

3.3 Closures

© Dept. of Computer Science and Engineering, GUB


1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script>
7 function outer() {
8 let count = 0;
9 return function inner() {
10 count++;
11 return count;
12 };
13 }
14
15 const increment = outer();
16 console.log(increment()); // Output: 1
17 console.log(increment()); // Output: 2
18 </script>
19
20 </body>
21
22 </html>

3.4 Prototypes and Inheritance

1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script>
7 function Person(name) {
8 this.name = name;
9 }
10
11 Person.prototype.greet = function () {
12 return ‘Hello, ${this.name}‘;
13 };
14
15 const john = new Person(’John’);
16 console.log(john.greet()); // Output: Hello, John
17 </script>
18
19 </body>
20
21 </html>

3.5 JavaScript Modules

1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script type="module">

© Dept. of Computer Science and Engineering, GUB


7 // Inline module example
8 export function add(a, b) {
9 return a + b;
10 }
11
12 import { add } from ’./file1.js’;
13 console.log(add(2, 3)); // Output: 5
14 </script>
15
16 </body>
17
18 </html>

This requires file1.js to contain the add function.

3.6 Advanced Array Methods


map(), filter(), reduce() function.
1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script>
7 const numbers = [1, 2, 3];
8
9 // map
10 const squared = numbers.map(num => num * num);
11 console.log(squared); // Output: [1, 4, 9]
12
13 // filter
14 const even = numbers.filter(num => num % 2 === 0);
15 console.log(even); // Output: [2]
16
17 // reduce
18 const sum = numbers.reduce((total, num) => total + num, 0);
19 console.log(sum); // Output: 6
20 </script>
21
22 </body>
23
24 </html>

3.7 Promises and Fetch API


3.7.1 Fetch API

1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script>
7 fetch(’https://jsonplaceholder.typicode.com/posts/1’)
8 .then(response => response.json())
9 .then(data => console.log(data))
10 .catch(error => console.error(’Error:’, error));
11 </script>

© Dept. of Computer Science and Engineering, GUB


12
13 </body>
14
15 </html>

3.7.2 Promise Chaining

1 <!DOCTYPE html>
2 <html>
3
4 <body>
5
6 <script>
7 fetch(’https://jsonplaceholder.typicode.com/posts/1’)
8 .then(response => response.json())
9 .then(data => {
10 console.log(’First fetch:’, data);
11 return fetch(’https://jsonplaceholder.typicode.com/users/1’);
12 })
13 .then(userResponse => userResponse.json())
14 .then(user => console.log(’Second fetch:’, user))
15 .catch(error => console.error(’Error:’, error));
16 </script>
17
18 </body>
19
20 </html>

4 JavaScript HTML DOM


The Document Object Model (DOM) allows you to manipulate HTML elements using JavaScript.
1 <!DOCTYPE html>
2 <html>
3 <body>
4 Name:<input type="text" id="mytext" value ="abcd">
5
6 <p>click the button to change the value of text field</p>
7 <button onclick=myfunction1()> try it </button>
8
9 <p id="demo">JS DOM</p>
10 <p>click the button to change color of p tag</p>
11 <button onclick="myfunction2()">try it to change tag color</button>
12
13 <ul>
14 <li>Coffee</li>
15 <li>Tea</li>
16 <li>Milk</li>
17 </ul>
18
19 button onclick="myFunction3()">Try it</button>
20
21 <p id="demo2"></p>
22 <script>
23 function myfunction1(){
24 document.getElementById("mytext").value="wxyz";
25 }

© Dept. of Computer Science and Engineering, GUB


26
27 document.getElementById("demo").innerHTML="html element change";
28
29 function myfunction2(){
30 var x=document.getElementsByTagName("p");
31
32 for(var i=0;i<x.length;i++){
33 x[i].style.color="red";
34 }
35 }
36
37 function myFunction3() {
38 var x = document.getElementsByTagName("LI");
39 document.getElementById("demo").innerHTML = x[0].innerHTML;
40 }
41 </script>
42
43
44 </body>
45 </html>

5 Input/Output
Output of the program is given below.

Figure 1: HTML DOM

© Dept. of Computer Science and Engineering, GUB


6 Discussion & Conclusion
This lab introduced advanced JavaScript concepts such as ES6 features, asynchronous programming, clo-
sures, prototypes, and DOM manipulation. These features are essential for writing efficient and maintainable
JavaScript code, and they allow dynamic interaction with web pages.

7 Lab Task (Please implement yourself and show the output to the
instructor)
Write the following JavaScript inside a <script> tag:

7.1 Task 1:
1. Create an asynchronous function using async/await that fetches data from an API.
2. Manipulate the DOM by dynamically creating new HTML elements based on the fetched data.

7.2 Task 2:
1. Implement a JavaScript program to count and display the items of a dropdown list, in an alert window.
2. Implement a JavaScript program to change the attribute value of image tag.

8 Lab Exercise (Submit as a report)


• Write a JavaScript function to get the values of First and Last name of the following form.
• Write a JavaScript program to count and display the items of a dropdown list, in an alert window.
• Write a module that exports a class with a constructor and methods, utilizing fetch to retrieve data and
update the DOM based on the data retrieved.

9 Policy
Copying from internet, classmate, seniors, or from any other source is strongly prohibited. 100% marks will be
deducted if any such copying is detected.

© Dept. of Computer Science and Engineering, GUB

You might also like