0% found this document useful (0 votes)
11 views72 pages

Wdf Unit 2 Digital Notes

This document is a confidential educational guide for the RMK Group of Educational Institutions, detailing the course 'Web Development Frameworks' for the 2023-2027 batch. It includes information on course objectives, prerequisites, syllabus, faculty members, course outcomes, and assessment schedules. The course aims to equip students with hands-on experience in modern web development technologies, particularly focusing on JavaScript frameworks like React.

Uploaded by

oopsitsmysteria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views72 pages

Wdf Unit 2 Digital Notes

This document is a confidential educational guide for the RMK Group of Educational Institutions, detailing the course 'Web Development Frameworks' for the 2023-2027 batch. It includes information on course objectives, prerequisites, syllabus, faculty members, course outcomes, and assessment schedules. The course aims to equip students with hands-on experience in modern web development technologies, particularly focusing on JavaScript frameworks like React.

Uploaded by

oopsitsmysteria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Please read this disclaimer before proceeding:

This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
22CS403/22IT403/22IT407
WEB DEVELOPMENT FRAMEWORKS
(Lab Integrated)
Batch / Year / Semester: 2023-2027 / II / 4

Name of the Faculty Members


RMKEC
1.Dr. S.D. Lalitha, ASP, CSE, RMKEC
2.Ms. V. Haritha, AP, CSE, RMKEC
3.Ms. J. Latha, AP, CSE,RMKEC
4.Dr. G. Manikandan, Professor, ADS, RMKEC
5.Dr. Gladiss Merlin N R, ASP, ADS, RMKEC
6.Dr. A. Ponmalar, ASP, ADS,RMKEC
7.Dr. P. Umaeswari, ASP, CSBS, RMKEC
8.Dr. M.S. Girija ,ASP,CSD,RMKEC
9.Ms. M. Kanniga Parameshwari, AP ,IT, RMKEC
RMDEC
1.Dr. G. Amudha , Professor & Head, CSBS, RMDEC
2.Dr. P.M. Joe Prathap , Professor, CSE, RMDEC
3.Mrs. D. Vishnu Sakthi , AP, CSE, RMDEC
4.Dr. K. Roslin Dayana, ASP, CSE, RMDEC
5.Dr. R .Jothilakshmi , ASP, IT, RMDEC
6.Dr. B. Kalpana, ASP, IT, RMDEC
7.Dr. K. Sudharson, ASP, AIML, RMDEC
8.Dr. K. Sudha, ASP, CSBS, RMDEC
RMKCET
1.Dr. Sivasubramanian R , ASP, CSE, RMKCET
2.Dr. Prasath R, ASP, CSE, RMKCET
3.Ms. Saranya R, ASP, CSE, RMKCET
4.Dr. L. Maria Michael Visuwasam, ASP, ADS, RMKCET

4
1. CONTENTS
S.NO. CONTENTS PAGE NO

1 Contents 5
2 Course Objectives 6
3 Pre Requisites 7
4 Syllabus 8
5 Course Outcomes 13
6 CO- PO/PSO Mapping 14
7 Lecture Plan 15
8 Activity Based Learning 16
9 Lecture Notes 18-46
10 Assignment – 1 to 5 47-48
11 Part A Questions & Answers 49-63
12 Part B Questions 64
Supportive Online Certification 65
13
Courses
14 Real time Applications 66-67
15 Contents Beyond the Syllabus 68
16 Assessment Schedule 69
Prescribed Text Books & Reference 70
17
Books
18 Mini Project – 1 to 5 71

5
2. COURSE OBJECTIVES
OBJECTIVES:

The Course will enable learners:

● To understand web semantics and related tools and framework

● Able to get hands on latest JS based web frameworks

● To develop a scalable and responsive web application

● To develop an industry ready application web enterprise feature

6
3. PRE REQUISITES

• Pre-requisite Chart

22CS303/22IT403/22IT407

WEB DEVELOPMENT FRAMEWORKS

22CS102
-
SOFTWARE DEVELOPMENT PRACTICES

7
4. Syllabus
22IT407 – WEB DEVELOPMENT FRAMEWORKS (Lab Integrated) – L T P C - 3 0 2 4

UNIT I - ADVANCED JAVASCRIPT – 9+6


Introduction to HTML5 and CSS3, Media Queries, JS, DOM, BootStrap, Variables, Loops,
Operators, Scope, Hoisting, Arrays, Spread, REST, DeStructuring.
List of Exercise/Experiments
1) Create a JS Object for Bank Account (w attributes like à customer name,
account type, balance, data of creation, bank name, branch name, pan card
number). Using JS Object keyword, try to perform following activities
➢ List down all the entries of the bank object
➢ Check the existence of a key
➢ If key found, get the value for the key
2) Spread Operator
➢ Merge Customer and Account Arrays
➢ Update the Customer Object with the new values
➢ Develop a function that takes a Spread Argument and calculates total balance.
UNIT II - INTRODUCTION TO REACTJS - 9+6
Class-Inheritance, Methods, Extended Class-Map, filter and Reduce Functions, Functions -
Arrow Functions, Lambda Expressions, REST - Introduction, Why JSX, Hello World Apps,
Project Structure
List of Exercise/Experiments
1) Create a list of Bank Objects (same kind of object you used in above
lab, but in an array format)
➢ Display the banks where balance is greater than 200
➢ deduct 10% of the Bank account balance, as part of monthly service
fees
➢ Display the banks where balance is greater than 200 and branch
code is “Chennai”
➢ Add a new Bank to the given array
➢ Delete a bank from the array (use splice operator)
➢ Calculate the total balance of all bank accounts

6
4. Syllabus
2) Develop a Scientific calculator that does following operations
➢ Rounded Value
➢ Area of Circle
➢ Calculating of Sin, Cos and Tan functions
➢ Permiter of a Rectangle
➢ Employ Arrow functions
➢ Employ HOC
UNIT III - REACT COMPONENTS – 9+6
Class vs Functional Components, Lifecycle methods - React Class Based Components
– component DidMount, WillUpdate, shouldupate, didcatchetc - State - UseState,
UseRef, USeEffect, UseHistory Usage and Props(difference, when to use what,
mutable or immutabilty,direction of flow), PropTypes, Auxillary Components,
Controlled and Uncontrolled Components, Component Interaction (Parent to Child and
Child to Parent), Iteration & Conditional Response
List of Exercise/Experiments
1) Create a collection of Customer by using
➢ Weak Map and Map Collection in JS
➢ Show Case the different feature set of the same.
2) Add Login Page, Dash Board Page, Admin Page
➢ Enable React Routing
➢ Add React Protected Route, for authorization
UNIT IV - REACT LIBRARY – I – 9+6
Event Bubbleup - Component Wrapper - Integration of CSS Modules - Forms
Validations(YUP, Formik, Standard), Events Handling, Data Binding - Redux
List of Exercise/Experiments
1) Develop a React application that has User Registration Form w field
level validations, data submission to a rest api end point, boot strap for
responsive.
➢ Use YUP or Formik to implement the same.
4. Syllabus
2) Build a Redux Counter Application
Requirements:
➢ React application with Redux integrated.
➢ A counter with:
➢ Increment button
➢ Decrement button
➢ Reset button
➢ Display the current counter value.
UNIT V - REACT LIBRARY – II – 9+6
Custom Hooks, HTTP - Fetch, Axios, and Context API, Services, Behaviour Subjects -
StateLess, StateFulll and Container Components, Error Handling - Build, Env, CORS, Unit
Testing w React Testing Library - Introduction to react-native - Introduction to StoryBook
List of Exercise/Experiments
1) Employ backend API for Login Page functionality (authentication). Post login,
store the user context (received from the back end server) in browser’s session
storage as objects. And use the same as creds during protected route verification.
➢ On the dashboard page, have a grid of Students. The data has to be bought
from backend api
➢ Employ useref, useeffect & usestate, and useHistory
2) Enable Exception Handling
3) Enable HOC and Aux Components
4) Implement React-Testing Library
5) Basic Context Setup
Objective: Set up a React Context to manage theme (light or dark).
➢ Create a ThemeContext using React.createContext.
➢ Create a provider component ThemeProvider with state to toggle
between "light" and "dark" themes.
➢ Use the context in a functional component to display the current theme.
➢ Add a button to toggle the theme.
4. SYLLABUS
Business Use Case Implementations

1) Student Management System

2) Retail Bank System

3) E-Commerce System
4) Student LMS Management System
TOTAL:45+30=75 PERIODS
TEXTBOOK:
1. David Flanagan, Javascript The Definitive Guide, Paperback, 7th Edition, 2020.
2. David Choi ,Full-Stack React, TypeScript, and Node: Build cloud-ready web
applications using React 17 with Hooks and GraphQL Paperback – Import, 18
December 2020.
3. Mehul Mohan, Advanced Web Development with React Paperback – 1 January
2020.
E-RESOURCES:
1.Parental Website - https://reactjs.org/
2.The Road to Learn React: Your journey to master plain yet pragmatic React.js by
Robin Wieruch
3.Learning React: Functional Web Development with React and Redux by Alex Banks
and Eve Porcello
4. Learning React by KirupaChinnathambi
5. "React Up & Running" by StoyanStefanov
6. https://www.edureka.co/reactjs-redux-certification-training
7. CodePen
8. CodeSandbox (Preferred)
9. Stackblitz

11
4. SYLLABUS
LIST OF EQUIPMENTS:
• NodeJS (v9.11.2)
• Github as code repository
• Visual studio code as IDE
• RTL as unit testing framework
• Responsive design w bootstrap
• ReactJS installation (v17)
• Chrome / FIreFox Browsers (latest)
• Responsive using Media Queries & Bootstrap Material & Antdesign
• Design based Apps.

12
5. Course Outcomes
Course Outcomes with Knowledge Levels:
CO1: Personalize web pages using text formatting, graphics, audio,
and video. - K3
CO2: Hands on knowledge on Rest API , propTypes. - K3
CO3: Able to develop a web application using latest React
Framework – K3
CO4: Apply various React features including functions,
components, and services. – K3
CO5: Able to develop application using ReactJshooks. – K3
CO6: Design and integrate complex web components to enhance
user interface and user experience in React applications. – K5

11
6. CO-PO/PSO Mapping

PROGRAM OUTCOMES PSO


CO
PO PO PO PO PO PO PO PO PO PO PO PO P P P
S S S
1 2 3 4 5 6 7 8 9 10 11 12 O O O
1 2 3
CO1 3 3 3 1 1 - - - 2 1 - 1 - - -

CO2 3 2 3 1 2 - - - 2 1 - 1 - - -

CO3 3 3 3 1 2 - - 1 2 1 - 1 - - -

CO4 3 3 3 1 2 - - - 2 1 - 1 - - -

CO5 3 3 3 1 2 - - 1 2 1 - 1 - - -

CO6 2 3 3 - 3 - - 1 2 2 - 3 - - -

CO 2.83 2.83 3.00 1.00 2.00 - - 1.00 2.00 1.17 - 1.33 - - -

Correlation Level
1. Slight (Low)
2. Moderate (Medium)
3. Substantial (High) ,
If there is no correlation, put “-“.

12
7. LECTURE PLAN
Sl. Taxono
No. of. Proposed Actual Pertaining Mode of
No Topics my
Periods Date Date CO Delivery
. Level

MD 1,
1 Class 1 06.01.2025 06.01.2025 CO2, CO3 K3
MD 4

Inheritance, MD 1,
2 1 07.01.2025 07.01.2025 CO2,CO3 K3
Methods MD 4

Map, filter and MD 1,


3 1 08.01.2025 21.12.2025 CO2,CO3 K3
Reduce Functions MD 4

MD 1,
4 Functions 1 09.01.2025 23.12.2025 CO2,CO3 K3
MD 4

MD 1,
5 Arrow Functions 2 10.01.2025 26.12.2025 CO2,CO3 K3
MD 4

Lambda MD 1,
6 1 11.01.2025 11.01.2025 CO2,CO3 K3
Expressions , REST MD 4

Introduction, Why MD 1,
7 1 20.01.2025 20.01.2025 CO2,CO3 K3
JSX MD 4

Hello World Apps MD 1,


8 1 21.01.2025 21.01.2025 CO2,CO3 K3
using Reactjs MD 4

MD 1,
9 Project Structure 1 25.01.2025 25.01.2025 CO2,CO3 K3
MD 4

From From
10
06.01.2025 06.01.2025
- Lab Exercises 6 CO2,CO3 K3 Iamneo
To To
15
25.01.2025 25.01.2025

* MD1 – Oral Presentation


* MD 4 – Hands on using any IDE
8. Activity Based Learning

Common Activities

Learning Methods Activities

Class Exercises, Challenge Yourself,


Learn by Solving Problems Practice At Home exercises posted in
iamneo Portal

Knowledge Check / MCQ Using


Learn by Questioning
iamneo portal and RMK Nextgen App

Learn by Hands on Practice available in iamneo Portal


8. Activity Based Learning
Unit II - Activity
Enable the students to master the CSS
https://cssgridgarden.com/
https://blog.logrocket.com/build-tic-tac-toe-game-react-hooks/
9. Lecture Notes
Unit II
INTRODUCTION TO REACTJS

18
9. Lecture Notes - INTRODUCTION TO REACTJS
INTRODUCTION TO REACTJS

➢ ECMAScript 2015, also known as ES6, introduced JavaScript Classes.

➢ JavaScript Classes are templates for JavaScript Objects.

2.1 CLASS IN JS

JavaScript Class Syntax

➢ Use the keyword class to create a class.


➢ Always add a method named constructor():

Syntax

class ClassName {
constructor() { ... }
}

Example
class Students {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
• The example above creates a class named " Students ".
• The class has two initial properties: "name" and "year".
Using a Class
When you have a class, you can use the class to create objects:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Classes</h1>
<p>Creating two car objects from a car class:</p>
<p id="demo"></p>
<script> Output
class Car {
constructor(name, year) { Creating two car objects from
this.name = name; a car class:
this.year = year;
} Ford Audi
}
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
document.getElementById ("demo").innerHTML =
myCar1.name + " " + myCar2.name;
</script>
</body>
</html>
9. Lecture Notes - INTRODUCTION TO REACTJS
The Constructor Method

The constructor method is a special method:


• It has to have the exact name "constructor"
• It is executed automatically when a new object is created
• It is used to initialize object properties
• If you do not define a constructor method, JavaScript will add an empty
constructor method.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Class Methods</h1>
<p>How to define and use a Class method.</p>

<p id="demo"></p>

<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;

}
age() {
const date = new Date();
return date.getFullYear () - this.year;
}
}

const myCar = new Car("Ford", 2014);


document.getElementById ("demo").innerHTML =
"My car is " + myCar.age() + " years old.";
</script>
Output
</body>
</html> JavaScript Class Methods
How to define and use a Class
method.
My car is 9 years old.
9. Lecture Notes - INTRODUCTION TO REACTJS

"use strict“

The syntax in classes must be written in "strict mode".


You will get an error if you do not follow the "strict mode" rules.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Classes uses "strict mode"</h1>

<p>In a JavaScript Class you cannot use variable without declaring it.</p>

<p id="demo"></p>
Output
<script>
class Car { JavaScript Classes uses "strict mode“
constructor(name, year) {
this.name = name; In a JavaScript Class you cannot use
this.year = year; variable without declaring it.

} My car is 9 years old.


age() {
// date = new Date(); // This will not work
const date = new Date(); // This will work
return date.getFullYear () - this.year;
}
}

const myCar = new Car("Ford", 2014);


document.getElementById ("demo").innerHTML =
"My car is " + myCar.age() + " years old.";
</script>

</body>
</html>
9. Lecture Notes - INTRODUCTION TO REACTJS
2.2 JAVASCRIPT CLASS INHERITANCE

To create a class inheritance, use the extends keyword.


A class created with a class inheritance inherits all the methods from another
class:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Class Inheritance</h1>

<p>Use the "extends" keyword to inherit all methods from another class.</p>
<p>Use the "super" method to call the parent's constructor function.</p>

<p id="demo"></p>

<script>
class Car {
constructor(brand) {
this.carname = brand; Output
}
present() { JavaScript Class Inheritance
return 'I have a ' + this.carname;
} Use the "extends" keyword to inherit
} all methods from another class.

class Model extends Car { Use the "super" method to call the
constructor(brand, mod) { parent's constructor function.
super(brand);
this.model = mod; I have a Ford, it is a Mustang
}
show() {
return this.present() + ', it is a ' + this.model;
}
}

const myCar = new Model("Ford", "Mustang");


document.getElementById("demo").innerHTML = myCar.show();
</script>

</body>
</html>

• The super() method refers to the parent class.


• By calling the super() method in the constructor method, we call the parent's
constructor method and gets access to the parent's properties and methods.
9. Lecture Notes - INTRODUCTION TO REACTJS
class Animal {
constructor(name) {
this.speed = 0;
this.name = name; }
run(speed) {
this.speed = speed;
alert(`${this.name} runs with speed ${this.speed}.`); }
stop() {
this.speed = 0;
alert(`${this.name} stands still.`); }
}
let animal = new Animal("My animal");
Here’s how we can represent animal object and Animal class graphically:

• And we would like to create another class Rabbit.


• As rabbits are animals, Rabbit class should be based on Animal, have access to animal
methods, so that rabbits can do what “generic” animals can do.
• The syntax to extend another class is: class Child extends Parent.
• Let’s create class Rabbit that inherits from Animal:
class Rabbit extends Animal
{
hide() {
alert(`${this.name} hides!`); }
}
9. Lecture Notes - INTRODUCTION TO REACTJS
let rabbit = new Rabbit("White Rabbit");
rabbit.run(5); // White Rabbit runs with speed 5.
rabbit.hide(); // White Rabbit hides!

2.3 JAVASCRIPT METHODS

In JavaScript, objects can also contain functions. For example,

// object containing method


const person = {
name: 'John',
greet: function() { console.log('hello'); }
};

In the above example, a person object has two keys (name and greet), which have a string
value and a function value, respectively. Hence basically, the JavaScript method is an object
property that has a function value.

<!DOCTYPE html>
<html>
<body>

<h1>The JavaScript <i>this</i> Keyword</h1>


<p>In this example, <b>this</b> refers to the <b>person</b> object.</p>
<p>Because <b>fullName</b> is a method of the person object.</p>

<p id="demo"></p>
Output

<script> The JavaScript this Keyword


// Create an object:
const person = { In this example, this refers to
firstName: "John", the person object.
lastName: "Doe",
id: 5566, Because fullName is a method of the
fullName : function() { person object.
return this.firstName + " " + this.lastName;
} John Doe
};

// Display data from the object:


document.getElementById("demo").innerHTML = person.fullName();
</script>

</body>
</html>
9. Lecture Notes - INTRODUCTION TO REACTJS
What is this?

• In JavaScript, the this keyword refers to an object.

• Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.

Alone, this refers to the global object.

In a function, this refers to the global object.

In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.

Methods like call(), apply(), and bind() can refer this to any object.

Note
this is not a variable. It is a keyword. You cannot change the value of this.

Accessing Object Methods

• You can access an object method using a dot notation.

• The syntax is: objectName.methodKey()

• you can access property by calling an objectName and a key. You can access a method by
calling an objectName and a key for that method along with (). For example,

// accessing method and property


const person = {
name: 'John',
greet: function() { console.log('hello'); }
};

// accessing property
person.name; // John

// accessing method
person.greet(); // hello
9. Lecture Notes - INTRODUCTION TO REACTJS
JavaScript Built-In Methods

let number = '23.32';


let result = parseInt(number);

console.log(result); // 23

Here, the parseInt() method of Number object is used to convert numeric string value to an
integer value.

Refer here for more built in JS Methods


https://www.w3schools.com/js/js_object_methods.asp

2.4 EXTENDED CLASS

❑ The extends keyword is used to create a child class of another class (parent).
❑ The child class inherits all the methods from another class.
❑ Inheritance is useful for code reusability: reuse properties and methods of an existing
class when you create a new class.
❑ Note: From the example above; The super() method refers to the parent class. By calling
the super() method in the constructor method, we call the parent's constructor method
and gets access to the parent's properties and methods.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Class Inheritance</h2>

<p>Use the "extends" keyword to inherit all methods from another class.</p>
<p>Use the "super" method to call the parent's constructor function.</p>

<p id="demo"></p>
9. Lecture Notes - INTRODUCTION TO REACTJS
<script>
class Car {
constructor(brand) {
this.carname = brand;
Output
}
present() {
JavaScript Class Inheritance
return 'I have a ' + this.carname;
Use the "extends" keyword to inherit all
}
methods from another class.
}

Use the "super" method to call the parent's


class Model extends Car {
constructor function.
constructor(brand, mod) {
super(brand);
I have a Ford, it is a Mustang
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}

mycar = new Model("Ford", "Mustang");


document.getElementById("demo").innerHTML = mycar.show();
</script>

</body>
</html>

Syntax

class childClass extends parentClass


9. Lecture Notes - INTRODUCTION TO REACTJS
2.5 MAP , FILTER, REDUCE FUNCTIONS

The map(), reduce() and filter() are array functions that transform the array according to
the applied function and return the updated array. They are used to write simple, short
and clean codes for modifying an array instead of using the loops.

2.5.1 map()
It applies a given function on all the elements of the array and returns the updated array.
It is the simpler and shorter code instead of a loop. The map is similar to the following
code:
arr = new Array(1, 2, 3, 6, 5, 4);
for(let i = 0; i < 6; i++)
{
arr[i] *= 3;
}

Syntax:
array.map(function_to_be_applied)
array.map(function (args) { // code; })

Example:
function triple(n){
return n*3;
}
arr = new Array(1, 2, 3, 6, 5, 4);

var new_arr = arr.map(triple)


console.log(new_arr);

Output: [ 3, 6, 9, 18, 15, 12 ]


9. Lecture Notes - INTRODUCTION TO REACTJS

Consider a scenario in which we have multiple records of students and each


student record has a name, ID, and marks attribute.
let studentRecords = [ {name: 'John', id: 123, marks : 98 },
{name: 'Baba', id: 101, marks : 23 },
{name: 'yaga', id: 200, marks : 45 },
{name: 'Wick', id: 115, marks : 75 } ]

Problem Statement: We are interested in retrieving only the name of the


students and all the names should be in caps.
Expected Result: ['JOHN', 'BABA', 'YAGA', 'WICK']
Pretty simple right? There are multiple ways to achieve this. Let’s go through them one by
one.
1.Traditionalfor()loop
let names = [];
for (let index = 0; index < studentRecords.length; index++){
names.push(studentRecords[index].name.toUpperCase());
}console.log(names); // logs: [ 'JOHN', 'BABA', 'JOHN', 'WICK' ]
2.for(...of)
let names = []
for (const student of studentRecords) {
names.push(student.name.toUpperCase());
}
console.log(names); // logs: [ 'JOHN', 'BABA', 'JOHN', 'WICK' ]
3.forEach()
let names = []
studentRecords.forEach( student => {
names.push(student.name.toUpperCase());
})
console.log(names); // logs: +-[ 'JOHN', 'BABA', 'JOHN', 'WICK' ]
In all the above-mentioned approaches, we have to first create an empty array to save our
result. Moreover, In both, for(…of) and for() we have to explicitly iterate through the
arrays, making our code a lot messier.
9. Lecture Notes - INTRODUCTION TO REACTJS
Solution using map() →

let names = studentRecords.map( stu => stu.name.toUpperCase());


console.log(names); // logs: [ 'JOHN', 'BABA', 'JOHN', 'WICK' ]
The above piece of code shows how concise and elegant our code becomes when we use
the map function and when we don’t need to define an empty array.
Working of map():
Array.map( callback, thisValue )

❑ map() takes two arguments, callback and optional object value (by default the callback
is bound to this).
❑ map() executes the provided callback at each element of an array and returns the new
value to the resultant array.
❑ When thisValue is not provided, the callback function will bind itself to the object which
called it (this value depends on caller expression). In our example “thisValue” will bind
itself to “studentRecords”.

2.5.2 filter()

• filter() returns only those elements from array which fulfils the provided criteria.

• Problem Statement: Suppose we have the same dataset as above but this
time we want to get the details of students who scored more than 50 marks.

Expected Result: [{name: 'John', id: 123, marks : 98 },{name: 'Wick', id: 115, marks : 75
}]
Solution:
Now we use filter() to select records which fulfills the given condition (that is, marks > 50).
let names = studentRecords.filter(stu => stu.marks > 50);
console.log(names);
// logs: [ { name: 'John', id: 123, marks: 98 },{ name: 'Wick', id: 115, marks: 75 }]
9. Lecture Notes - INTRODUCTION TO REACTJS
Problem Statement: Retrieve the details of students who scored more than 50
marks and have id greater than 120.
let names = studentRecords.filter(stu => stu.marks > 50 && stu.id > 120)
console.log(names); //logs: [ { name: 'John', id: 123, marks: 98 } ]
Solution: As shown in the above piece of code, using filter() with multiple conditions to filter
data, we can solve this problem very efficiently.

Working of filter()
filter() takes the callback function which returns a bool value. If the provided callback returns
true, then the object is added to the resultant array. Otherwise, the object is ignored.

2.5.3 reduce()
❑ Just like map() and filter(), reduce() also executes the callback for each element of the
array. To better understand reduce, we first need to understand two terms: “accumulator”
and “reducer”.
❑ The accumulator is the value that we end up with, and the reducer is what action we will
perform in order to get to one value. You must remember that a reducer will always return
only one value, hence the name “reduce”. It’s time to deep dive into an example!

Problem Statement: Consider the same scenario we have discussed above, but
this time we would like to know the sum total of the marks of the students.

let totalMarks = studentRecords.reduce( ((acc,emp) => acc+emp.marks), 0)


console.log(totalMarks);// logs: 241

Solution: As shown in the above piece of code, using reduce() we were easily able to get
the desired result in a simple and robust way.

Working of reduce():
Array.reduce( (accumulator,curr_value) => expression ), intialValue)
9. Lecture Notes - INTRODUCTION TO REACTJS
Let’s understand the working of reduce step by step:
1) reduce() takes the accumulator, current value, expression and the initialValue as a
parameter used to initialize the accumulator (notice that we have passed initialValue =
0 in our example).
2) reduce() takes the first element of an array as the current value and the accumulator, and
then performs the required operation (as with the addition of two values in our
example), and saves the result in the accumulator.
3) The accumulator is then replaced by the previously calculated accumulator and the
current value is set to the second element of the array. Again, the required operation is
performed and the accumulator is updated with the new result.
4) Step 3 is repeatedly executed through to the last element of the array.
5) Finally, the accumulator value is returned by the function.
To compare our understanding with the actual working of reduce(), let’s observe the values
of the “accumulator” and “curr_value” at each iteration for the above example.

let totalMarks =
studentRecords.reduce( function(accumulator,curr_value){
console.log(`accumulator: ${accumulator}, curr_value:$ curr_value.marks}`);
return accumulator + curr_value.marks;}, 0)
console.log(totalMarks);
// logs -------accumulator: 0 , curr_value: 98
accumulator: 98 , curr_value: 23
accumulator: 121 , curr_value: 45
accumulator: 166 , curr_value: 75
241

It is evident from the above logs that the accumulator starts with an initial value of 0 and, at
every step, its value is updated by the sum of its “previous value” and “curr_value”.
9. Lecture Notes - INTRODUCTION TO REACTJS
2.6 ARROW FUNCTIONS

❑ An arrow function expression is a compact alternative to a traditional function


expression, with some semantic differences and deliberate limitations in usage:
❑ Arrow functions don't have their own bindings to this, arguments, or super, and should
not be used as methods.
❑ Arrow functions cannot be used as constructors. Calling them with new throws
a TypeError. They also don't have access to the new.target keyword.
❑ Arrow functions cannot use yield within their body and cannot be created as generator
functions.
❑ Arrow function {()=>} is concise way of writing Javascript functions in shorter
way. Arrow functions were introduced in the ES6 version. They make our code more
structured and readable.
❑ Arrow functions are anonymous functions i.e. functions without a name and are not
bound by an identifier. Arrow functions do not return any value and can be declared
without the function keyword. They are also called Lambda Functions.

Syntax:

const foo = () => { console.log( "Hi Buddy!" ); }

Before Arrow With Arrow Function

hello = function() hello = () =>


{ {
return "Hello World!"; return "Hello World!";
} }
9. Lecture Notes - INTRODUCTION TO REACTJS

There are three parts to an Arrow Function or Lambda Function:


❑ Parameters: Any function may optionally have the parameters.
❑ Fat arrow notation/lambda notation: It is the notation for the arrow (=>).
❑ Statements: It represents the instruction set of the function.

In the following example, we are defining three functions that show Function
Expression, Anonymous Function, and Arrow Function.

// function expression
var myfun1 = function show() {
console.log("It is a Function Expression");
}

// Anonymous function
var myfun2 = function () {
console.log("It is an Anonymous Function");
}
//Arrow function
var myfun3 = () => {
console.log("It is an Arrow Function");
};
myfun1();
myfun2();
myfun3();
Arrow Function with Parameters
If you require to pass more than one parameter by using an arrow function, then you have
to pass them within the parentheses.

var show = (a,b,c) => {


console.log(a + " " + b + " " + c );
}
show(100,200,300);
Output
100 200 300
9. Lecture Notes - INTRODUCTION TO REACTJS

Arrow function with Rest parameters:


❑ Rest parameters do not restrict you to pass the number of values in a function, but all
the passed values must be of the same type. We can also say that rest parameters act as
the placeholders for multiple arguments of the same type.
❑ For declaring the rest parameter, the parameter name should be prefixed with the spread
operator that has three periods (not more than three or not less than three).
❑ You can see the illustration for the same in the following example:
var show = (a, ...args) => {
console.log(a + " " + args);
}
show(100,200,300,400,500,600,700,800);

Output

100 200,300,400,500,600,700,800

Advantages of Arrow Functions

1. It reduces the code size: When we use the syntax of arrow function, the size of the code
gets reduced. We can write less amount of code by using the arrow function.
2. Return statement and Functional braces are optional for single line functions:In ES5, we
need to define the return statement in the functions, but in ES6, we do not require to
define the return statement for single-line functions. Functional braces are also optional for
the single-line functions.
9. Lecture Notes - INTRODUCTION TO REACTJS

2.7 LAMBDA EXPRESSIONS IN JAVASCRIPT

❑ A lambda expression is a code you enter to define a short function. A lambda function is
mostly present in modern languages (Ruby, Javascript, Java..). It’s just an expression that
creates a function.
❑ It is very important that programming languages ​support first-class functions, which
natively pass functions as arguments to other functions or assign them to variables. This
is source code text passed to the compiler and recognized using a specific syntax. (In
Javascript, this is technically called an arrow function expression/declaration.) At runtime,
the expression is evaluated as a lambda function in memory.
❑ A lambda function is a short and anonymous function that takes one or more parameters
and contains a single expression. Basically, you can pass a function as a parameter to
another function. Because functions are treated as objects in JavaScript, they can be
passed to and returned from other functions to create lambda functions.

Advantages of Javascript Lambda Functions:

▪ Lambda functions are pure functions in Javascript.


▪ Lambda functions are easy to read.
▪ Lambda functions are easy to cache.
Syntax:
function(arg1, arg2...argn) expression

Example 1: In this example, the arrow function is used for showing lambda expression.
let multiply = (a, b) => a * b;
console.log(multiply(5, 9));

Output:

45
9. Lecture Notes - INTRODUCTION TO REACTJS

Example 2: In this example, an anonymous function is used which shows the lambda
expression.
const Names = [
'Mansi',
'Gaurav',
'Akansha',
'Sanya'
];
console.log(Names.map(Names => Names.length));

Output:

[ 5, 6, 7, 5 ]

2.8 REST API

Every developer who wants to build modern, robust web applications with React must
understand how to consume APIs to fetch data into their React applications.

What is a REST API?


❑ If you've ever spent any time programming or researching programming, you've likely
come across the term "API."
❑ API stands for Application Programming Interface. It is a medium that allows different
applications to communicate programmatically with one another and return a response in
real time.
❑ Roy Fielding defined REST in 2000 as an architectural style and methodology commonly
used in the development of internet services, such as distributed hypermedia systems. It
is an acronym that stands for "REpresentational State Transfer."
❑ When a request is made via a REST API, it sends a representation of the resource's
current state to the requester or endpoint. This state representation can take the form of
JSON (JavaScript Object Notation), XML, or HTML.
❑ JSON is the most widely used file format because it is language-independent and can be
read by both humans and machines.
9. Lecture Notes - INTRODUCTION TO REACTJS
For example:

[
{
"userId": 1,
"id": 1,
"title": "sunt excepturi",
"body": "quia et suscipit\nsuscipit recusandae “
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil"
}
]

How to Consume REST API’s in React


You can consume REST APIs in a React application in a variety of ways, but in this guide, we
will look at two of the most popular approaches: Axios (a promise-based HTTP client) and
Fetch API (a browser in-built web API).

How to Consume APIs Using The Fetch API

❑ The Fetch API is a JavaScript built-in method for retrieving resources from a server or an
API endpoint. It's built-in, so you don't need to install any dependencies or packages.
❑ The fetch() method requires a mandatory argument, which is the path or URL to the
resource you want to fetch. Then it returns a Promise so you can handle success or failure
using the then() and catch() methods.
❑ A basic fetch request is very simple to write and looks like the below code. We are simply
fetching data from a URL that returns data as JSON and then logging it to the console:

fetch('https://jsonplaceholder.typicode.com/posts?_limit=10')
.then(response => response.json())
.then(data => console.log(data));
9. Lecture Notes - INTRODUCTION TO REACTJS

2.9 WHY JSX?

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any
createElement() and/or appendChild() methods. JSX converts HTML tags into react elements.
You are not required to use JSX, but JSX makes it easier to write React applications.

Without JSX JSX

const myElement = React.createElement('h1', const myElement =


{}, 'I do not use JSX!'); <h1>I Love JSX!</h1>;
const root = const root =
ReactDOM.createRoot(document.getElementB ReactDOM.createRoot(document.getElementB
yId('root')); yId('root'));
root.render(myElement); root.render(myElement);

import React from 'react';


import ReactDOM from 'react-dom/client';
const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);

OUTPUT
• Apples
• Bananas
• Cherries
9. Lecture Notes - INTRODUCTION TO REACTJS
❑ React embraces the fact that rendering logic is inherently coupled with other UI logic: how
events are handled, how the state changes over time, and how the data is prepared for display.
❑ Instead of artificially separating technologies by putting markup and logic in separate files,
React separates concerns with loosely coupled units called “components” that contain both. We
will come back to components in a further section, but if you’re not yet comfortable putting
markup in JS, this talk might convince you otherwise.
❑ React doesn’t require using JSX, but most people find it helpful as a visual aid when working
with UI inside the JavaScript code. It also allows React to show more useful error and warning
messages.

Embedding Expressions in JSX


In the example below, we declare a variable called name and then use it inside JSX by wrapping it
in curly braces:
const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;

You can put any valid JavaScript expression inside the curly braces in JSX.
For example, 2 + 2, user.firstName, or formatName(user) are all valid JavaScript expressions.
In the example below, we embed the result of calling a JavaScript function, formatName(user),
into an <h1> element.

function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = {
firstName: 'Harper',
lastName: 'Perez'
};
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
9. Lecture Notes - INTRODUCTION TO REACTJS

JSX is an Expression Too

❑ After compilation, JSX expressions become regular JavaScript function calls and evaluate to
JavaScript objects.
❑ This means that you can use JSX inside of if statements and for loops, assign it to variables,
accept it as arguments, and return it from functions:

function getGreeting(user) {
if (user) {
return <h1>Hello, {formatName(user)}!</h1>;
}
return <h1>Hello, Stranger.</h1>;
}
Specifying Attributes with JSX
▪ You may use quotes to specify string literals as attributes:
const element = <a href="https://www.reactjs.org"> link </a>;
▪ You may also use curly braces to embed a JavaScript expression in an attribute:
const element = <img src={user.avatarUrl}></img>;
▪ Don’t put quotes around curly braces when embedding a JavaScript expression in an
attribute. You should either use quotes (for string values) or curly braces (for expressions),
but not both in the same attribute.

Warning:
Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming
convention instead of HTML attribute names.
For example, class becomes className in JSX, and tabindex becomes tabIndex.
9. Lecture Notes - INTRODUCTION TO REACTJS
Characteristics of JSX:
❖ JSX is not mandatory to use there are other ways to achieve the same thing but using JSX
makes it easier to develop react application.
❖ JSX allows writing expression in { }. The expression can be any JS expression or React
variable.
❖ To insert a large block of HTML we have to write it in a parenthesis i.e, ().
❖ JSX produces react elements.
❖ JSX follows XML rule.
❖ After compilation, JSX expressions become regular JavaScript function calls.
❖ JSX uses camelcase notation for naming HTML attributes. For example, tabindex in HTML is
used as tabIndex in JSX.

2.10 HELLO WORLD APPS


❑ React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It
lets you compose complex UIs from small and isolated pieces of code called “components”.
❑ React has a few different kinds of components, but we’ll start
with React.Component subclasses:
class ShoppingList extends React.Component {
render() {
return (
<div className="shopping-list">
<h1>Shopping List for {this.props.name}</h1>
<ul>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
</ul>
</div>
);
}
}
// Example usage: <ShoppingList name="Mark" />
9. Lecture Notes - INTRODUCTION TO REACTJS
❑ Here, ShoppingList is a React component class, or React component type. A component
takes in parameters, called props (short for “properties”), and returns a hierarchy of views
to display via the render method.
❑ The render method returns a description of what you want to see on the screen. React
takes the description and displays the result. In particular, render returns a React element,
which is a lightweight description of what to render. Most React developers use a special
syntax called “JSX” which makes these structures easier to write. The <div /> syntax is
transformed at build time to React.createElement('div'). The example above is equivalent
to:
return React.createElement('div', {className: 'shopping-list'},
React.createElement('h1', /* ... h1 children ... */),
React.createElement('ul', /* ... ul children ... */)
);

➢ create-react-app is a command to create a React.js project with default configuration.


Create-react-app will help in running react applications. Command will be executed on npm
or yarn
➢ If npm and node.js is installed on computer, install create-react-app globally with command
npm install –g create-react-app
➢ Creation of project − to create a project once above commands are executed, run below
command
npx create-react-app hello-world-example
➢ With create-react-app, webpack or babel required for using advanced JavaScript features
are preconfigured and we can only concentrate on writing code.
cd hello-world-example
➢ To execute the application, run the below command on terminal −
npm start
➢ npm start runs a live development server and the code changes will automatically refresh
the browser and reflect the changes.
➢ A browser window will be opened, if not opened automatically open a browser manually
and type url − localhost:3000 in the address bar. 3000 is the default port used in React
application. Port number can be changed if any issue with port number.
9. Lecture Notes - INTRODUCTION TO REACTJS
The default text on application run is shown below –

To update open the project using any code editor tools e.g. visual studio code
Open the file App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Edit <code>src/App.js</code> and save to reload.</p>
<a className="App-
link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer">
Learn React
</a>
</header>
</div>
);
}
export default App;
9. Lecture Notes - INTRODUCTION TO REACTJS
Change the content of return statement to just hello World text −
import React from 'react';
import logo from './logo.svg';
import './App.css'; function App() {
return (
<div className="App">
Hello World !
</div>
);
}
export default App;
The text on the browser will be changed immediately

Why we use ReactJS?


The main objective of ReactJS is to develop User Interfaces (UI) that improves the speed of
the apps. It uses virtual DOM (JavaScript object), which improves the performance of the
app. The JavaScript virtual DOM is faster than the regular DOM. We can use ReactJS on the
client and server-side as well as with other frameworks. It uses component and data patterns
that improve readability and helps to maintain larger apps.
9. Lecture Notes - INTRODUCTION TO REACTJS

Key Benefits of React.js for Front-end Development

➢ Speed - Built based on the principal of Virtual Document Object Model (DOM), the
changes in UI elements renders fastest as compared to other web frameworks.
➢ Flexibility - React gives us flexibility to use any supporting library for styles,
animations, state management, even can render on the server using Node for Server-
Side Rendering (SSR).
➢ Performance - React creates an in-memory cache and computes the resulting changes,
and then updates the browser's displayed DOM . This process is called Reconciliation.
Thus, making it a high performant framework.
➢ Usability - React.js can be used to develop any front-end projects with good
interactivity for end users. It develops a new way of rendering websites, evolving the
responsive nature of web pages.
➢ Reusable Components - The components are basic building blocks in React. These
components are reusable and must be formed in the SRC folder following the Pascal
Case as its naming convention (capitalize camelCase). Components can be rendered
to a particular element in the DOM using the React DOM library. We can write and
reuse any number of components within our application.
The world’s most popular and finest web applications are built using React.js like
Facebook, Instagram, Netflix, Reddit etc. For more details, you can opt for a well-
curated online courses on React js and full stack development which is available on
KnowledgeHut.
10. ASSIGNMENT – 1 To 5
1) Create a list of Bank Objects (same kind of object you used in lab, but in
an array format)
❑ Display the banks where balance is greater than 200
❑ deduct 10% of the Bank account balance, as part of monthly service fees
❑ Display the banks where balance is greater than 200 and branch code is “Chennai”
❑ Add a new Bank to the given array
❑ Delete a bank from the array (use splice operator)
❑ Calculate the total balance of all bank accounts

2) Develop a Scientific calculator that does following operations.


❑ Rounded Value
❑ Area of Circle
❑ Calculating of Sin, Cos and Tan functions
❑ Permiter of an Rectangle
❑ Employ Arrow functions
❑ Employ HOC

3) Develop a Tic Tac Toe game using ES6 JS.


❑ Building a simple Tic Tac Toe game with JavaScript is another excellent project idea
you can finish in a single day.
❑ You will create a 3×3 grid where two players will take turns marking the grid with
cross and circle symbols. The first player to get three marks in a horizontal, vertical,
or diagonal row wins the game.
❑ Although the game seems simple, you need to figure out how to create the logic
that follows the game rules in JavaScript.
❑ Hence, before you start writing any code, break down the flow of the game into
logical steps first.
❑ For a simple game like Tic Tac Toe, I find it helpful to draw a small flow chart to
visualize the different outcomes of the game. When I can see the flow on paper, it’s
easier to start writing actual code.
10. ASSIGNMENT – 1 To 5

4) Develop a JavaScript palindrome checker.

A palindrome is a phrase or a word that reads the same backwards and forwards.
Building a simple palindrome checker is great practice for working with strings and
manipulating them with JavaScript. Plus, checking for palindromes can be a lot of fun!

5) JavaScript weather app project.

Building a weather app is a great project idea if you are new to JavaScript and you
don’t have too many projects in your portfolio just yet.
This project will teach you how to pull data from an API and display it dynamically on
your web page.
11. PART A : Questions & Answers
1. Define Class in JavaScript. (CO1, K2)

➢ Use the keyword class to create a class.


➢ Always add a method named constructor():

Syntax

class ClassName {
constructor() { ... }
}

Example
class Students {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
• The example above creates a class named " Students ".
• The class has two initial properties: "name" and "year".

2. What is constructor method (CO2,K2)


The Constructor Method

The constructor method is a special method:


• It has to have the exact name "constructor"
• It is executed automatically when a new object is created
• It is used to initialize object properties
• If you do not define a constructor method, JavaScript will add an empty constructor
method.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Class Methods</h1>
<p>How to define and use a Class method.</p>
<p id="demo"></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;

}
age() {
const date = new Date();
return date.getFullYear() - this.year;
}
}
11. PART A : Questions & Answers

const myCar = new Car("Ford", 2014);


document.getElementById("demo").innerHTML =
"My car is " + myCar.age() + " years old.";
</script>
</body>
</html>

3. Mention the ‘Use Strict’ concept in JS (CO1,K2)


The syntax in classes must be written in "strict mode".
You will get an error if you do not follow the "strict mode" rules.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Classes uses "strict mode"</h1>

<p>In a JavaScript Class you cannot use variable without declaring it.</p>

<p id="demo"></p>

<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;

}
age() {
// date = new Date(); // This will not work
const date = new Date(); // This will work
return date.getFullYear() - this.year;
}
}

const myCar = new Car("Ford", 2014);


document.getElementById("demo").innerHTML =
"My car is " + myCar.age() + " years old.";
</script>

</body>
</html>
11. PART A : Questions & Answers

4. What is inheritance in JS. (CO1,K2)


To create a class inheritance, use the extends keyword.

A class created with a class inheritance inherits all the methods from another class:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Class Inheritance</h1>

<p>Use the "extends" keyword to inherit all methods from another class.</p>
<p>Use the "super" method to call the parent's constructor function.</p>

<p id="demo"></p>

<script>
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}

class Model extends Car {


constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}

const myCar = new Model("Ford", "Mustang");


document.getElementById("demo").innerHTML = myCar.show();
</script>

</body>
</html>
11. PART A : Questions & Answers

5. Write the JS program for the above diagram (CO1,K2)


class Animal {
constructor(name) {
this.speed = 0;
this.name = name;
}
run(speed) {
this.speed = speed;
alert(`${this.name} runs with speed ${this.speed}.`);
}
stop() {
this.speed = 0;
alert(`${this.name} stands still.`);
}}
let animal = new Animal("My animal");

Here’s how we can represent animal object and Animal class graphically:
11. PART A : Questions & Answers
6. Mention the role of ‘this’. (CO1,K2)
In an object method, this refers to the object.
Alone, this refers to the global object.

In a function, this refers to the global object.

In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.

Methods like call(), apply(), and bind() can refer this to any object.

7. What are JavaScript Built-In Methods

let number = '23.32';


let result = parseInt(number);

console.log(result); // 23

Here, the parseInt() method of Number object is used to convert numeric string value to
an integer value.
Refer here for more built in JS Methods
https://www.w3schools.com/js/js_object_methods.asp
8. How to Accessing Object Methods

• You can access an object method using a dot notation.


• The syntax is: objectName.methodKey()
• you can access property by calling an objectName and a key. You can access a method
by calling an objectName and a key for that method along with (). For example,

// accessing method and property


const person = {
name: 'John',
greet: function() { console.log('hello'); }
};

// accessing property
person.name; // John

// accessing method
person.greet(); // hello
11. PART A : Questions & Answers
9 . What is EXTENDED CLASS ? (CO1,K2)

❑ The extends keyword is used to create a child class of another class (parent).
❑ The child class inherits all the methods from another class.
❑ Inheritance is useful for code reusability: reuse properties and methods of an existing
class when you create a new class.
❑ Note: From the example above; The super() method refers to the parent class. By
calling the super() method in the constructor method, we call the parent's constructor
method and gets access to the parent's properties and methods.
Syntax
class childClass extends parentClass

10 . Mention map synatx with example using following diagram.

Syntax:
array.map(function_to_be_applied)
array.map(function (args) { // code; })

Example:
function triple(n){
return n*3;
}
arr = new Array(1, 2, 3, 6, 5, 4);
var new_arr = arr.map(triple)
console.log(new_arr);

Output: [ 3, 6, 9, 18, 15, 12 ]


11. PART A : Questions & Answers
11. Problem Statement: We are interested in retrieving only the name of the
students and all the names should be in caps.
Expected Result: ['JOHN', 'BABA', 'YAGA', 'WICK']
Pretty simple right? There are multiple ways to achieve this. Let’s go through them one by
one.
1.Traditionalfor()loop
let names = [];
for (let index = 0; index < studentRecords.length; index++){
names.push(studentRecords[index].name.toUpperCase());
}console.log(names); // logs: [ 'JOHN', 'BABA', 'JOHN', 'WICK' ]
2.for(...of)
let names = []
for (const student of studentRecords) {
names.push(student.name.toUpperCase());
}console.log(names); // logs: [ 'JOHN', 'BABA', 'JOHN', 'WICK' ]
3.forEach()
let names = []
studentRecords.forEach( student => {
names.push(student.name.toUpperCase());
})console.log(names); // logs: +-[ 'JOHN', 'BABA', 'JOHN', 'WICK’ ]

12. Problem Statement: Suppose we have the same dataset as above but this
time we want to get the details of students who scored more than 50 marks.

Expected Result: [{name: 'John', id: 123, marks : 98 },{name: 'Wick', id: 115, marks : 75
}]
Solution: Now we use filter() to select records which fulfills the given condition (that
is, marks > 50).
let names = studentRecords.filter(stu => stu.marks > 50);console.log(names);//
logs: [ { name: 'John', id: 123, marks: 98 },{ name: 'Wick', id: 115, marks: 75 }]
11. PART A : Questions & Answers
13. Problem Statement: Retrieve the details of students who scored more than 50
marks and have id greater than 120.
let names = studentRecords.filter(stu => stu.marks > 50 && stu.id > 120)
console.log(names); //logs: [ { name: 'John', id: 123, marks: 98 } ]
Solution: As shown in the above piece of code, using filter() with multiple conditions to filter
data, we can solve this problem very efficiently.
Working of filter()
filter() takes the callback function which returns a bool value. If the provided callback returns
true, then the object is added to the resultant array. Otherwise, the object is ignored.
14. What is reduce() ?
❑ Just like map() and filter(), reduce() also executes the callback for each element of the
array. To better understand reduce, we first need to understand two terms: “accumulator”
and “reducer”.
❑ The accumulator is the value that we end up with, and the reducer is what action we will
perform in order to get to one value. You must remember that a reducer will always return
only one value, hence the name “reduce”. It’s time to deep dive into an example!
15. Problem Statement: Consider the same scenario we have discussed above, but
this time we would like to know the sum total of the marks of the students.
let totalMarks = studentRecords.reduce( ((acc,emp) => acc+emp.marks), 0)
console.log(totalMarks);// logs: 241
Solution: As shown in the above piece of code, using reduce() we were easily able to get the
desired result in a simple and robust way.
Working of reduce():
Array.reduce( (accumulator,curr_value) => expression ), intialValue)

16. Mention ARROW FUNCTIONS with syntax.


❑ An arrow function expression is a compact alternative to a traditional function expression,
with some semantic differences and deliberate limitations in usage:
❑ Arrow functions don't have their own bindings to this, arguments, or super, and should not
be used as methods.
❑ Arrow functions cannot be used as constructors. Calling them with new throws a TypeError.
They also don't have access to the new.target keyword.
11. PART A : Questions & Answers
❑ Arrow functions cannot use yield within their body and cannot be created as generator
functions.
❑ Arrow function {()=>} is concise way of writing Javascript functions in shorter way. Arrow
functions were introduced in the ES6 version. They make our code more structured and
readable.
❑ Arrow functions are anonymous functions i.e. functions without a name and are not bound
by an identifier. Arrow functions do not return any value and can be declared without the
function keyword. They are also called Lambda Functions.

Syntax:

const foo = () => { console.log( "Hi Buddy!" ); }

17. Mention BEFORE & AFTER ARROW FUNCTIONS syntax .

Before Arrow
hello = function()
{
return "Hello World!";
}
With Arrow Function

hello = () =>
{
return "Hello World!";
}
18. What are three parts to an Arrow Function or Lambda Function?
❑ Parameters: Any function may optionally have the parameters.
❑ Fat arrow notation/lambda notation: It is the notation for the arrow (=>).
❑ Statements: It represents the instruction set of the function.

19. Mention Anonymous Function, and Arrow Function.?

// function expression
var myfun1 = function show() {
console.log("It is a Function Expression");
}
11. PART A : Questions & Answers
// Anonymous function
var myfun2 = function () {
console.log("It is an Anonymous Function");
}
//Arrow function
var myfun3 = () => {
console.log("It is an Arrow Function");
};
myfun1();
myfun2();
myfun3();
Arrow Function with Parameters
If you require to pass more than one parameter by using an arrow function, then you have
to pass them within the parentheses.
var show = (a,b,c) => {
console.log(a + " " + b + " " + c );
}
show(100,200,300);
Output
100 200 300

20. Mention Arrow function with Rest parameters. (CO2,K2)


❑ Rest parameters do not restrict you to pass the number of values in a function, but all the
passed values must be of the same type. We can also say that rest parameters act as the
placeholders for multiple arguments of the same type.
❑ For declaring the rest parameter, the parameter name should be prefixed with the spread
operator that has three periods (not more than three or not less than three).
❑ You can see the illustration for the same in the following example:
var show = (a, ...args) => {
console.log(a + " " + args);
}
show(100,200,300,400,500,600,700,800);

Output

100 200,300,400,500,600,700,800
11. PART A : Questions & Answers
21. Mention Advantages of Arrow function :
1. It reduces the code size: When we use the syntax of arrow function, the size of the code
gets reduced. We can write less amount of code by using the arrow function.
2. Return statement and Functional braces are optional for single line functions:In ES5, we
need to define the return statement in the functions, but in ES6, we do not require to
define the return statement for single-line functions. Functional braces are also optional for
the single-line functions.

22. What is LAMBDA EXPRESSIONS IN JAVASCRIPT?


❑ A lambda expression is a code you enter to define a short function. A lambda function is
mostly present in modern languages (Ruby, Javascript, Java..). It’s just an expression
that creates a function.
❑ It is very important that programming languages ​support first-class functions, which
natively pass functions as arguments to other functions or assign them to variables. This
is source code text passed to the compiler and recognized using a specific syntax. (In
Javascript, this is technically called an arrow function expression/declaration.) At runtime,
the expression is evaluated as a lambda function in memory.
❑ A lambda function is a short and anonymous function that takes one or more parameters
and contains a single expression. Basically, you can pass a function as a parameter to
another function. Because functions are treated as objects in JavaScript, they can be
passed to and returned from other functions to create lambda functions.
11. PART A : Questions & Answers
23. Advantages of Javascript Lambda Functions:
▪ Lambda functions are pure functions in Javascript.
▪ Lambda functions are easy to read.
▪ Lambda functions are easy to cache.
Syntax:
function(arg1, arg2...argn) expression
24. What is a REST API? (CO2,K2)
❑ If you've ever spent any time programming or researching programming, you've likely
come across the term "API."
❑ API stands for Application Programming Interface. It is a medium that allows different
applications to communicate programmatically with one another and return a response in
real time.
❑ Roy Fielding defined REST in 2000 as an architectural style and methodology commonly
used in the development of internet services, such as distributed hypermedia systems. It
is an acronym that stands for "REpresentational State Transfer."
❑ When a request is made via a REST API, it sends a representation of the resource's
current state to the requester or endpoint. This state representation can take the form of
JSON (JavaScript Object Notation), XML, or HTML.
❑ JSON is the most widely used file format because it is language-independent and can be
read by both humans and machines.
25. How to Consume APIs Using The Fetch API?
❑ The Fetch API is a JavaScript built-in method for retrieving resources from a server or an
API endpoint. It's built-in, so you don't need to install any dependencies or packages.
❑ The fetch() method requires a mandatory argument, which is the path or URL to the
resource you want to fetch. Then it returns a Promise so you can handle success or
failure using the then() and catch() methods.
❑ A basic fetch request is very simple to write and looks like the below code. We are simply
fetching data from a URL that returns data as JSON and then logging it to the console:

fetch('https://jsonplaceholder.typicode.com/posts?_limit=10')
.then(response => response.json())
.then(data => console.log(data));
11. PART A : Questions & Answers
26. WHY JSX used?

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any
createElement() and/or appendChild() methods. JSX converts HTML tags into react elements.
You are not required to use JSX, but JSX makes it easier to write React applications.
import React from 'react';
import ReactDOM from 'react-dom/client';
const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
OUTPUT
• Apples
• Bananas
• Cherries
27. Define Embedding Expressions in JSX.
In the example below, we declare a variable called name and then use it inside JSX by
wrapping it in curly braces:
const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;
You can put any valid JavaScript expression inside the curly braces in JSX.
For example, 2 + 2, user.firstName, or formatName(user) are all valid JavaScript expressions.
In the example below, we embed the result of calling a JavaScript
function, formatName(user), into an <h1> element.
11. PART A : Questions & Answers

function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = {
firstName: 'Harper',
lastName: 'Perez'
};
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
28. Mention Characteristics of JSX: (CO2,K2)
❖ JSX is not mandatory to use there are other ways to achieve the same thing but using
JSX makes it easier to develop react application.
❖ JSX allows writing expression in { }. The expression can be any JS expression or React
variable.
❖ To insert a large block of HTML we have to write it in a parenthesis i.e, ().
❖ JSX produces react elements.
❖ JSX follows XML rule.
❖ After compilation, JSX expressions become regular JavaScript function calls.
❖ JSX uses camelcase notation for naming HTML attributes. For example, tabindex in HTML
is used as tabIndex in JSX.
29. Create HELLO WORLD APPS using React. (CO3,K5)
❑ React is a declarative, efficient, and flexible JavaScript library for building user interfaces.
It lets you compose complex UIs from small and isolated pieces of code called
“components”.
❑ React has a few different kinds of components, but we’ll start
with React.Component subclasses:
11. PART A : Questions & Answers
class ShoppingList extends React.Component {
render() {
return (
<div className="shopping-list">
<h1>Shopping List for {this.props.name}</h1>
<ul>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
</ul>
</div>
);
}}
// Example usage: <ShoppingList name="Mark" />
30. What are the Key Benefits of React.js for Front-end Development? (CO3,K2)
➢ Speed - Built based on the principal of Virtual Document Object Model (DOM), the
changes in UI elements renders fastest as compared to other web frameworks.
➢ Flexibility - React gives us flexibility to use any supporting library for styles, animations,
state management, even can render on the server using Node for Server-Side
Rendering (SSR).
➢ Performance - React creates an in-memory cache and computes the resulting changes,
and then updates the browser's displayed DOM . This process is called Reconciliation.
Thus, making it a high performant framework.
➢ Usability - React.js can be used to develop any front-end projects with good interactivity
for end users. It develops a new way of rendering websites, evolving the responsive
nature of web pages.
➢ Reusable Components - The components are basic building blocks in React. These
components are reusable and must be formed in the SRC folder following the Pascal
Case as its naming convention (capitalize camelCase). Components can be rendered to
a particular element in the DOM using the React DOM library. We can write and reuse
any number of components within our application.
12. PART B : Questions

Q. CO
Questions K Level
No. Level

1 Discuss in detail the evolution of Javascript in day to day life. CO1 K2

2 Explain JAVASCRIPT CLASS INHERITANCE. CO1 K2

3 Explain the Constructor Method and ‘use strict’ method. CO1 K2

What are Key Benefits of React.js for Front-end


4 CO3 K2
Development? Explain in detail.
5 Explain in detail about JAVASCRIPT METHODS CO1 K2
6 Explain in detail map(), filter(), reduce(). CO1 K2
7 Mention Arrow function in detail. CO1 K2

8 What is a REST API? How to Consume APIs Using The Fetch API. CO2 K3

9 Develop a Student Portfolio application using React. CO3 K5

An e-commerce website built using React, where we can filter

clothes products using their customer preferred sizes as M, L

or XL etc. We have a button called “Add to cart” below each


10 CO3 K5
product shown on the web page, once user selects any

product, it will go to cart. At the end it can be used to

checkout.

What is LAMBDA EXPRESSIONS IN JAVASCRIPT ? Explain it


11. CO1 K2
with example.
13. SUPPORTIVE ONLINE CERTIFICATION COURSES

• Building RESTful APIs Using Node.js and Express

- coursera

https://www.coursera.org/learn/building-restful-apis-
using-nodejs-and-
express?authType=google&completeMode=existingCour
seraAccount

• React Basics - coursera

https://www.coursera.org/learn/react-basics

65
14. REAL TIME APPLICATIONS

1) A WEB APPLICATION PROVIDING RANGE OF OPTIONS TO CAR BUYERS


Car selling website is where the customer can buy and sell their car. This website is
user friendly and ease to use for any customer, it has effective search box to get the
precise and suitable car for the user. A rich search facility is always there from where
customer can search vehicle via category, keywords, price range, brand, types, fuel
types, etc. The website displays information of the customer support person on the
homepage so that user can directly contact them or meet them which help in
decreasing the communication gap. This website also provides a facility for road side
assistance. The social media plugin will help the company to know their popularity
over the social media.

2) PLAY YOUR FANTASY SPORTS ONLINE USING WEB APPLICATION


This application is developed for users who are interested in playing fantasy sports
online. Users can play fantasy sports with close friends or people you met over the
internet. Users can create their own leagues and can invite friends to play in their
league or they can play in others leagues. Users can easily change the league size,
payment deadlines, payout verifications and payout timelines. This system guarantee
the professional safekeeping of the funds through full-featured security measures.
User can withdraw funds from their account. User can refer a friend to play a
particular league.

3) BOOTSTRAP & RESPONSIVE DESIGN


Responsive web design is a way of making a single website that works effectively on
both desktop browsers and the myriad of mobile devices on the market. It involves
having a website that enhances the viewing experience, irrespective of which device
is being used. Bootstrap makes the front-end web development faster and easier. It is
made for the users of all skill levels, devices of all shapes and projects of all sizes. It is
considered the most popular HTML, CSS, and JavaScript framework for developing
responsive & mobile-first websites. With a responsive website design, you don't have
to have worry about having different websites for various devices or making sure that
your website runs properly on a mobile device.
14. REAL TIME APPLICATIONS

At Spaculus, we can incorporate your new website design or we modify it and make it
responsive if you already own a website. Our team of experts uses various tools and
technologies to make your website more accessible such as media queries, flexible
grid based layouts that use re-sizing and flexible images & media.

4) Navigating the Internet


HTML is an essential element in navigating between web pages. Navigation is possible
using the hypertext concept. The linking is also simpler. From the internet user’s point
of view, they click on a text which takes them to the next page. HTML facilitates
navigation by hyperlinking with the help of an anchor tag.
<a href="geeksforgeeks.org"> Click here to open! </a>Navigation can increase
visitors to a website. It increases user activity on the website. It also helps the web
user to look at the content structure and organization.

5)Storage Function in the Browser


Storage of data in the browser was tedious in the past. For a user to save the data of
the browser that persists between two sessions, the user’s cookies or infrastructure is
to be built from the server end. This process has now been eased with
HTML5. HTML5 has roped in new features. Such storage features are localStorage
and IndexDB.
The web storage objects window.localStorage and window.sessionStorage store data
with no expiration date and storage for one session respectively. The localStorage
object will have the data saved even when the browser is closed. setItem and
removeItem are the functions commonly used to store and remove data from the
storage. Also, the most important part is that these features are supported by all
browsers.

To Store – localStorage.setItem(“username”, “Nisha”);


To Retrieve – document.getElementById(“result”).innerHTML =
localStorage.getItem(“username”);
To Remove – localStorage.removeItem(“username”);
15. CONTENT BEYOND SYLLABUS
Writing React without JSX using React.createElement() :
What is React.createElement()?
The React.createElement() function is a core API in React that creates a virtual DOM
representation of a UI element.
It takes three arguments:
Type: The type of the HTML element or React component (e.g., 'div', 'h1', or a
custom component).
Props: An object representing the properties (attributes) and event handlers for
the element.
Children: The child elements or content nested within the element. This can be
a string, a React element, or an array of React elements.
Syntax :
React.createElement(
type, // Type of element or component (e.g., 'div', 'span', MyComponent)
props, // Object containing element attributes (e.g., { className: 'my-class' })
...children // Content or child elements
);
write a simple "Hello, World!" React component without JSX:
Using JSX:
const HelloWorld = () => <h1>Hello, World!</h1>;
Without JSX:
const HelloWorld = () => {
return React.createElement(
'h1', // Type of element
null, // No props for this element
'Hello, World!' // Child content
);
};
Rendering the Component:
ReactDOM.render(
React.createElement(HelloWorld),
document.getElementById('root’)
); 68
16. ASSESSMENT SCHEDULE

• Tentative schedule for the Assessment During


2024-2025 Even Semester

Name of the
S.NO Start Date End Date Portion
Assessment
As per schedule after
1 Unit Test 1 UNIT 1
Unit I completion
2 IAT 1 28.01.2025 03.02.2025 UNIT 1 & 2

As per schedule after


3 Unit Test 2 UNIT 3
Unit III completion

4 IAT 2 10.03.2025 15.03.2025 UNIT 3 & 4

5 Model 03.04.2025 17.04.2025 ALL 5 UNITS

163

69
17. PRESCRIBED TEXT BOOKS
&
REFERENCE BOOKS
TEXT BOOKS:

JAVASCRIPT THE DEFINITIVE GUIDE 7/ED Paperback – 15 June 2020

Full-Stack React, TypeScript, and Node: Build cloud-ready web applications using React 17
with Hooks and GraphQL Paperback – Import, 18 December 2020

Advanced Web Development with React Paperback – 1 January 2020

REFERENCES:

PARENTAL WEBSITE - https://reactjs.org/

The Road to Learn React: Your journey to master plain yet pragmatic React.js by Robin
Wieruch

Learning React: Functional Web Development with React and Redux by Alex Banks and Eve
Porcello

Learning React by Kirupa Chinnathambi

"React Up & Running" by Stoyan Stefanov

https://www.edureka.co/reactjs-redux-certification-training

ONLINE LEARNING PLATFORMS :

CodePen,

CodeSandbox (ß Preferred)

Stackblitz.
18. MINI PROJECT – 1 to 5
1) HOW TO CREATE A COUNTER
Create applications that update the data of the page without needing a refresh. Also, you
can create applications that are customizable by the user and then change the layout of the
page without a refresh.

2) JAVASCRIPT CLOCK
Key concepts to be covered:
Variables
Conditional logic
Program flow
Functions

3)To-Do List
Implement a Liist to add, remove, and group items by using arrays, nested functions and
local storage API.

4) Tic_Tac-Toe
Implement the JavaScript code for Tic–Tac-Toeso with the options to set the difficulty level
as easy or hard, to set the players to be X or O and to remember the player won or drew &
play again.

5) Guess the Word


Implement the JavaScript code so that players start by entering a letter. If they guess
correctly, the letter appears in the word. If they guess incorrectly, they learn how many
guesses they have remaining. The player can also see which letters they’ve already
guessed. The game lets the player know whether they entered a non-alphabetic character!
Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
relianceon the contents of this information is strictly prohibited.

You might also like