Is - FSD Notes
Is - FSD Notes
1
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Syllabus:
Module-1 Basic JavaScript Instructions, Statements, Comments, Variables, Data Types, Arrays,
Strings, Functions, Methods & Objects, Decisions & Loops.
Module-2 Document Object Model: DOM Manipulation, Selecting Elements, Working with DOM Nodes,
Updating Element Content & Attributes, Events, Different Types of Events, How to Bind an Event to an
Element, Event Delegation, Event Listeners
Module-3 Form enhancement and validation. Introduction to MERN: MERN components, Server
less Hello world. React Components: Issue Tracker, React Classes, Composing Components,
Passing Data Using Properties, Passing Data Using Children, Dynamic Composition.
Module-4 React State: Initial State, Async State Initialization, Updating State, Lifting State Up,
Event Handling, Stateless Components, Designing Components, State vs. Props, Component
Hierarchy, Communication, Stateless Components.
Express, REST API, GraphQL, Field Specification, Graph Based, Single Endpoint, Strongly Typed,
Introspection, Libraries, The About API GraphQL Schema File, The List API, List API Integration,
Custom Scalar types, The Create API, Create API Integration, Query Variables, Input Validations,
Displaying Errors.
2
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
JavaScript: JavaScript is a versatile, object-oriented scripting language that enables the creation of
interactive web pages and runs seamlessly across multiple platforms. In addition to its client-side
capabilities, JavaScript has server-side variants like Node.js, which unlock enhanced website
functionality, enabling developers to craft more dynamic, engaging, and feature-rich online
experiences that go beyond simple file downloads.
Client-side JavaScript builds upon the core language by providing a set of objects that enable
control over the browser and its Document Object Model (DOM). With these extensions,
developers can create dynamic web applications that interact with users in various ways, such as
adding elements to HTML forms, handling user input, responding to mouse clicks, and reacting to
page navigation events. This allows for a more engaging and interactive user experience.
Server-side JavaScript expands the core language by introducing objects tailored for server-side
execution. These extensions empower applications to interact with databases, maintain session state
between invocations, and perform file operations on the server, thereby enabling more complex and
data-driven web applications. This allows developers to build robust, scalable, and dynamic server-
side logic that integrates seamlessly with various data sources and services.
Why JS?
1. Scripting language
2. Light weight and purely object based language
3. JS is high-level language which gets executed on the browser, to execute JS instructions it is
mandatory to translate JS instruction into machine understandable language, this job is done by JS
engine
4. client-side language
5. JS is loosely typed and dynamic typed language - To giving the functionality to the webpage,
without reloading the page It is case-sensitive (but html and CSS are casein sensitive)
6. It is interpreted language - means it is interpreted line by line or execute line by line
7. It is synchronous: it is follows only one stack; example books arrangement in library, (LIFO)
Last in first out: memory representation
2. It is multi-threaded It is single-threaded
3
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Declaring variables
Assigning values
Executing functions
Controlling flow (e.g., if/else, loops)
Manipulating data
These instructions are executed by the JavaScript engine, allowing the program to interact with
users, manipulate data, and produce desired outcomes. Think of them as individual commands that,
when combined, create a JavaScript program.
4
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
// Get the element that has an id of tiles then update its contents
var elTiles = document.getElementById('tiles');
elTiles.textContent = tiles;
// Get the element that has an id of subTotal then update its contents
var elSubTotal = document.getElementById('subTotal');
elSubTotal.textContent = '$' + subTotal;
// Get the element that has an id of shipping then update its contents
var elShipping = document.getElementById('shipping');
elShipping.textContent = '$' + shipping;
// Get the element that has an id of grandTotal then update its contents
5
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Syntax Basics
Understanding statements, variable naming, whitespace, and other basic JavaScript syntax.
A simple variable declaration
var foo = ’hello world ’;
Whitespace has no meaning outside of quotation marks
var foo = ’hello world ’;
Parentheses indicate precedence
2 * 3 + 5; // returns 11; multiplication happens first
2 * (3 + 5); // returns 16; addition happens first
Tabs enhance readability, but have no special meaning
var foo = function () {
console . log ( ’hello ’);
};
Object it is block of memory which has states (variables) and behaviour (methods), and stores in
key and value pair.
Console.log("Hello World")
Console. log ( “data” );
Console: It is object in JavaScript. It will help you (user/programmer) to uses variables and
functions present in the object.
Log: it is a function which accepts arguments. Log is member of console. (Present inside the
console)
Output methods:
There are five methods; Alert, Prompt, Confirm, Console.log, document.write
6
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
JavaScript Statements
Example:
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
JavaScript statements are composed of Values, Operators, Expressions, Keywords, and Comments.
The statements are executed, one by one, in the same order as they are written. JavaScript programs
and JavaScript statements are also called JavaScript code. Semicolons separate JavaScript
statements. Add a semicolon at the end of each executable statement. Ending statements with
semicolon is not required, but highly recommended.
// How to create variables:
var x;
let y;
// How to use variables:
x = 5;
y = 6;
let z = x + y;
7
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
JavaScript Values
The JavaScript syntax defines two types of values:
Fixed values
Variable values
Fixed values are called Literals.
Variable values are called Variables.
Comments
JavaScript comments serve as a valuable tool for clarifying and documenting code, making it easier
to understand and maintain. Additionally, comments can be strategically used to temporarily
disable code execution, allowing developers to test alternative implementations or troubleshoot
issues without permanently deleting code segments. This flexibility streamlines the development
and debugging process.
Single line comments start with //. Any text between // and the end of the line will be ignored by
JavaScript (will not be executed). This example uses a single-line comment before each code line:
Example
let x = 5; // Declare x, give it the value of 5
let y = x + 2; // Declare y, give it the value of x + 2
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
/*
This is a multi-line comment
that spans multiple lines
*/
Variables: variables are used to store and manipulate data. Variables can be declared in 4 ways:
Variables can be reassigned (except for const).
Variables can be declared without an initial value.
JavaScript is dynamically typed, meaning variable types can change during execution.
underscore character
Note: Because JavaScript is case-sensitive, variable names are case-sensitive.
8
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Variable Types
JavaScript variables can hold various data types, including:
Numbers
Strings
Booleans
Arrays
Objects
Null
Undefined
Data Types:
It is a type of data, every variable has datatype that represents what kind of data is being stored in a variable.
Types of Data Type: Primitive Data type, Non -Primitive Data type
-defined data type provided by JS language and
it is immutable.
Types: Number, String, Boolean, Null, Undefined, BigInt, Symbol
9
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
-Primitive Data user defined data type, it is also called as reference type, and created by programmer
and it is mutable.
Types: Arrays, objects and functions etc.
can be change
BigInt. number
less than 150 will be considered as Number data type. 1- number,1n- BigInt.
function.
Non-Primitive Datatype:
Arrays, functions and objects
Arrays: array is a single value, But in JS we use to store different elements i.e., heterogeneous
value.
Representing array in square braces []
Function: used to perform the operations.
Advantage: 1. code reusability
2. code extensibility or less coding
Operators
The operator = is used to assign values. The operator + is used to add values. The assignment operator = is
used to assign values to JavaScript variables. The arithmetic operator + is used to add values together.
Ex: y=5;
z=2;
x=y+z;
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
Operator Description Example Result
10
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
11
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Comparison operators can be used in conditional statements to compare values and take action depending
on the result: if (age<28)document.write(“too young”);
Logical Operators
Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the
table below explains the logical operators:
Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable
based on some condition
Syntax variablename=(condition)?value1:value2
If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value "Dear
President " else it will be assigned "Dear"
Strings: Sequence of characters is String, In JS String can be represented using ‘ ‘ ,” “, ` ` . Note: 1. The start
and end of a string must be done with the help of same quote.(`”,” ‘,’ “, these are not allowed.) 2. If a text
contains a single quote ten it can be represented using “ “.
Backtick: A Backtick can be a multi-line string. String represented using backtick is also known as
Template String.
The advantage of template string is we can substitute an expression in a string using ${expression}.
12
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
String Methods:
1.IndexOf()
Syntax: IndexOf(str/chr) user can give string or character, it will return index value.
Character which is not present in the string then the output will be -1. first occurrence value..
But it can take 1st and 2nd character too
2. lastindesxof()
3. search() is similar to indexof, it only first occurrence value. Accept the, first search character
only one character. It not
accept two argument
4. Str.length:To check the length of the String
var str= "JAVA SCRIPT"
console.log(str.length);
5. Slice: To check the character in the index, using this we can extract some part of string. It will
accept the first or start index
13
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
and last index. Last digit will be work as length- 1, if (5, 9) 5 to 9-1=8, we can pass both positive
and negative value
var a = str.slice(0,4);
console.log(a);
6.Uppercase
var a= str.toUpperCase("script");
console.log(a);
7.Lowercase
17
var a = str.toLowerCase("java");
console.log(a);
8. Concat
Addition of two strings
var a="Java"
var b=" Script"
console.log(a.concat(b));
9. charAT : it specifies the position of the character
var str="JavaScript";
var char=str.charAt(1);
console.log(char);//a
10.charCodeAT: it converts to the ASCII value to the specified character
var str="JavaScript";
var char=str.charCodeAt(1);
console.log(char); //97
1. it repeat the string 3 times.
var char=str.repeat(3);
console.log(char);//JavaScriptJavaScriptJavaScript
14
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
12.trim:It removes the space which is present at starting and endig position.
13.startWith
var car="JAVASCRIPT"
var char = str.startsWith(']');
console.log(char);
14.EndsWith
var car="JAVASCRIPT"
var char = str.endsWith(']');
console.log(char);
15. Split
Example 1:
var str=''MALL OF MYSORE';
var char=str.split('');
console.log(char);
Exampe 2:
var str='MALL OF MYSORE';
var char=str.split(' ');
18
console.log(char);// (2)[ 'MALL OF MYSORE']
Example 3:
var str='MALL OF MYSORE';
var char=str.split('| ');
console.log(char);// (1)[ 'MALL OF MYSORE']
16. Substring : substring () to extract the part of string, it is similar to slice but it won’t accept the
negative value or
.Substr(): start index and length of the character to be extracted. It will accept negative value.
using subscript [] we can access the character.
15
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Functions: In JavaScript, functions are blocks of code that can be executed multiple times from different
parts of a program.
Syntax:
Function identifier (parameter 1, parameterc2)
{
Statements / code;
}
Function Declaration
Functions can be declared using the function keyword:
JavaScript
function greet(name) {
console.log(`Hello, ${name}!`);
}
16
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Function Expression
Functions can also be defined as expressions:
JavaScript
let greet = function(name) {
console.log(`Hello, ${name}!`);
}
Arrow Functions
Arrow functions are a concise way to define functions, introduced in ECMAScript 2015 (ES6):
JavaScript
let greet = (name) => {
console.log(`Hello, ${name}!`);
}
Function Parameters
Functions can take parameters, which are values passed to the function when it's called:
JavaScript
function add(a, b) {
return a + b;
}
Function Return Values
Functions can return values using the return statement:
JavaScript
function square(x) {
return x * x;
}
Function Invocation
Functions can be invoked (called) using the function name followed by parentheses:
JavaScript
greet('John'); // Output: Hello, John!
Function Scope
Functions have their own scope, which means variables defined inside a function are not accessible
outside the function:
JavaScript
17
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
function example() {
let x = 10;
console.log(x); // Output: 10
}
console.log(x); // ReferenceError: x is not defined
Higher-Order Functions
Higher-order functions are functions that take other functions as arguments or return functions as
output:
JavaScript
function map(arr, fn) {
return arr.map(fn);
}
Anonymous Functions
Anonymous functions are functions without a name:
JavaScript
let numbers = [1, 2, 3].map(function(x) {
return x * x;
});
Immediately Invoked Function Expressions (IIFE)
IIFE is a function that is called immediately after its definition:
JavaScript
(function() {
console.log('Hello, World!');
})();
Objects
Objects are collections of key-value pairs, where each key is a string and each value can be any data
type, including functions:
JavaScript
let person = {
18
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
name: 'John',
age: 30,
occupation: 'Developer'
};
Methods
Methods are functions that are properties of an object:
let person = {
name: 'John',
age: 30,
occupation: 'Developer',
greet: function() {
console.log(`Hello, my name is ${this.name}!`);
}
};
Accessing Object Properties
Object properties can be accessed using dot notation or bracket notation:
console.log(person.name); // Output: John
console.log(person['age']); // Output: 30
Creating Objects
Objects can be created using object literals, constructor functions, or the Object.create() method:
let person = new Object();
person.name = 'John';
person.age = 30;
Object Methods
Objects have built-in methods, such as hasOwnProperty(), keys(), and values():
JavaScript
console.log(Object.keys(person)); // Output: ['name', 'age', 'occupation']
19
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Constructor Functions
Constructor functions are used to create objects with a specific structure:
JavaScript
function Person(name, age) {
this.name = name;
this.age = age;
}
let person = new Person('John', 30);
Prototypes
Prototypes are objects that serve as templates for other objects:
JavaScript
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}!`);
};
Inheritance
Inheritance allows objects to inherit properties and methods from parent objects:
function Employee(name, age, occupation) {
Person.call(this, name, age);
this.occupation = occupation;
}
Employee.prototype = Object.create(Person.prototype);
Object-Oriented Programming (OOP) Concepts
JavaScript supports OOP concepts, such as encapsulation, inheritance, and polymorphism:
class Person {
constructor(name, age) {
20
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}!`);
}
}
class Employee extends Person {
constructor(name, age, occupation) {
super(name, age);
this.occupation = occupation;
}
}
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You
can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
if statement - use this statement if you want to execute some code only if a specified condition is
true
if...else statement - use this statement if you want to execute some code if the condition is true
and another code if the condition is false
if...else if....else statement - use this statement if you want to select one of many blocks of code
to be executed
switch statement - use this statement if you want to select one of many blocks of code to be
executed
If Statement
You should use the if statement if you want to execute some code only if a specified condition is
true.
Syntax
if (condition)
21
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
{
code to be executed if condition is true
}
Example 1
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>
If...else Statement
If you want to execute some code if a condition is true and another code if the condition is not true,
use
the if....else statement.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example
<script type="text/javascript">
//If the time is less than 10,
22
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
23
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
Else
{
document.write("<b>Hello World!</b>");
}
</script>
24
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
code to be executed if n is
different from case 1 and 2
}
Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>
25
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Very often when you write code, you want the same block of code to run over and over again in a
row.
Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
In JavaScript there are two different kind of loops:
- loops through a block of code a specified number of times
- loops through a block of code while a specified condition is true
The for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
Example
Explanation: The example below defines a loop that starts with i=0. The loop will continue to run
as long
as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any comparing
statement.
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
26
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
Example
</html>
<body>
<script type="text/javascript">
var i=0;
while (i<=10)
27
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
28
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
}
while (var<=endvalue);
Example
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>
Result
The number is 0
29
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body></html>
Result
The number is 0
The number is 1
The number is 2
Continue
The continue command will break the current loop and continue with the next value.
Example
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
30
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
Module-2
Document Object Model: The Document object represents the entire HTML document and can be used to
access all elements in a page. The Document object is part of the Window object and is accessed through
the window.document property.
DOM Manipulation :In JavaScript, DOM (Document Object Model) manipulation is used to dynamically
change the structure and content of a web page.
, Selecting Elements, Working with DOM Nodes, Updating Element Content & Attributes, Events, Different
Types of Events, How to Bind an Event to an Element, Event Delegation, Event Listeners
Selecting Elements
31
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
To manipulate the DOM, you need to select the elements you want to work with:
Creating Elements
Adding Elements
You can add elements to the DOM using the appendChild() or insertBefore() methods:
parent.appendChild(newElement);
Removing Elements
You can remove elements from the DOM using the removeChild() or remove() methods:
parent.removeChild(child);
Modifying Elements
32
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
DOM nodes involves manipulating the elements and structure of a web page. Here's a comprehensive
overview:
Node Types
Node Properties
33
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Node Methods
Nodes have several methods that can be used to manipulate the DOM:
appendChild(): Adds a new child node to the end of the list of child nodes.
insertBefore(): Inserts a new child node before the specified child node.
element.appendChild(newElement);
Node Collections
console.log(elements[i]);
DOM Manipulation
element.appendChild(text);
34
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
element.setAttribute('class', 'new-class');
element.removeAttribute('class');
element.style.color = 'red';
element.classList.add('new-class');
element.classList.remove('old-class');
element.classList.toggle('active');
35
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
element.className = 'new-class';
element.classList.add('new-class');
element.classList.remove('old-class');
element.classList.toggle('active');
Events :
events are used to respond to user interactions, such as clicking a button, hovering over an element, or
submitting a form. OR
an Event is always the result of something a user does. For example, we've already seen Event Handlers like
onClick and onMouseOver that respond to mouse actions. Another type of Event, an internal change-of-
state to the page (completion of loading or leaving the page). An onLoad Event can be considered an
indirect result of a user action.
Event Types
document.getElementById('myButton').addEventListener('click', function() {
console.log('Button clicked');
});
OR
Types of events that can be triggered by user interactions, browser actions, or other events. Here's a
comprehensive overview:
Mouse Events
36
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
document.getElementById('myButton').addEventListener('click', function() {
console.log('Button clicked');
});
Keyboard Events
document.addEventListener('keydown', function(event) {
});
Form Events
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
console.log('Form submitted');
});
Document Events
window.addEventListener('load', function() {
37
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
console.log('Document loaded');
});
Touch Events
document.addEventListener('touchstart', function(event) {
console.log('Touch started');
});
Pointer Events
document.addEventListener('pointerdown', function(event) {
console.log('Pointer down');
});
Animation Events
document.addEventListener('animationstart', function(event) {
console.log('Animation started');
});
Transition Events
38
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
document.addEventListener('transitionstart', function(event) {
console.log('Transition started');
});
Binding an event to an element involves attaching a function to an event listener. Here's a step-by-step
guide:
element.addEventListener('click', function() {
console.log('Element clicked');
});
element.attachEvent('onclick', function() {
console.log('Element clicked');
});
function myFunction() {
console.log('Button clicked');
$('#myElement').on('click', function() {
console.log('Element clicked');
});
capture: A boolean value indicating whether the event should be captured or bubbled.
once: A boolean value indicating whether the event listener should be removed after the first invocation.
passive: A boolean value indicating whether the event listener should be passive.
39
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
element.addEventListener('click', function() {
console.log('Element clicked');
}, {
capture: true,
once: true,
passive: true
});
JavaScript
element.removeEventListener('click', function() {
console.log('Element clicked');
});
Event Delegation
Event delegation is a technique where an event listener is attached to a parent element instead of
individual child elements. When an event occurs on a child element, it bubbles up to the parent element
and triggers the event listener.
Attach an event listener to a parent element: Use addEventListener() to attach an event listener to a parent
element.
Use the event.target property: Inside the event listener, use the event.target property to access the child
element that triggered the event.
Check the target element: Use an if statement or other logic to check if the target element is the one you're
interested in.
document.getElementById('parent').addEventListener('click', function(event) {
if (event.target.classList.contains('child')) {
});
40
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Suppose you have a list of items and you want to handle clicks on each item. Instead of attaching an event
listener to each item, you can attach a single event listener to the parent list element and use event
delegation to handle clicks on each item.
HTML
<ul id="list">
</ul>
document.getElementById('list').addEventListener('click', function(event) {
if (event.target.classList.contains('item')) {
});
Event Listeners
element.addEventListener('click', function() {
console.log('Element clicked');
});
OR
Event listeners are functions that are attached to elements and executed when a specific event
occurs, such as a click, hover, or submit.
Types of Event Listeners
There are several types of event listeners, including:
Inline event listeners: Functions that are defined directly in the HTML code.
External event listeners: Functions that are defined in a separate JavaScript file.
Anonymous event listeners: Functions that are defined without a name.
41
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Module-3
Form enhancement and validation: Both are crucial for creating user-friendly and secure web applications.
Form Enhancement
Form enhancement involves adding functionality to forms to improve the user experience:
Form Validation
Form validation involves checking form data for errors and providing feedback to the user:
Client-side validation: Validation that occurs on the client-side (in the browser).
42
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Server-side validation: Validation that occurs on the server-side (on the server).
Validation types: Different types of validation, such as required, email, and password.
HTML5 validation: Using HTML5 validation attributes, such as required and pattern.
// HTML5 validation
// JavaScript validation
if (!email.includes('@')) {
e.preventDefault();
});
Example
Suppose you have a simple contact form with fields for name, email, and message. You can use JavaScript
to validate the form fields and provide feedback to the user.
<form id="contact-form">
<label for="name">Name:</label>
<label for="email">Email:</label>
43
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
<label for="message">Message:</label>
<button type="submit">Submit</button>
</form>
e.preventDefault();
} else if (!email.includes('@')) {
e.preventDefault();
});
MERN is a popular full-stack JavaScript framework used for building scalable and robust web applications.
MERN stands for MongoDB, Express.js, React.js, and Node.js. It's a collection of technologies that work
together to provide a comprehensive framework for building web applications.
MERN Components
React.js: A JavaScript library for building user interfaces and single-page applications.
Node.js: A JavaScript runtime environment that allows developers to run JavaScript on the server-side.
MongoDB
44
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
MongoDB is a NoSQL database that provides a flexible and scalable way to store data. Its key features
include:
Express.js
Express.js is a Node.js framework that provides a lightweight and flexible way to build web applications and
APIs. Its key features include:
Request and response objects: Provides a simple way to handle HTTP requests and responses.
React.js
React.js is a JavaScript library that provides a way to build user interfaces and single-page applications. Its
key features include:
State and props: Provides a way to manage state and props in components.
Node.js
Node.js is a JavaScript runtime environment that allows developers to run JavaScript on the server-side. Its
key features include:
Server less Hello world: a simple "Hello World" example using a serverless function in a MERN (MongoDB,
Express.js, React.js, Node.js) stack:
mongoose.connect('mongodb+srv://username:[email protected]/', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
45
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
message: String,
});
await helloWorld.save();
return {
statusCode: 200,
};
};
This is a basic serverless function written in Node.js that connects to a MongoDB database and saves a
"Hello World!" message.
React.js Frontend
function App() {
useEffect(() => {
axios.get('/api/hello-world')
.then((response) => {
setMessage(response.data.message);
})
.catch((error) => {
console.error(error);
46
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
});
}, []);
return (
<div>
<h1>{message}</h1>
</div>
);
This is a basic React.js application that makes a GET request to the serverless function and displays the
response.
const params = {
FunctionName: 'your-function-name',
InvocationType: 'RequestResponse',
};
if (err) {
console.error(err);
} else {
res.json(data.Payload);
});
});
47
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
app.listen(3000, () => {
});
React Components:
React components are reusable pieces of code that represent a part of your user interface. They can be
thought of as custom HTML elements that can contain other components.
Functional Components : These are the simplest type of component and are defined as a function.
Class Components : These are more complex components that are defined as a class.
Functional Components
Functional components are defined as a function and are the simplest type of component. They are easy to
write and understand.
function HelloWorld() {
Class Components
Class components are defined as a class and are more complex than functional components. They have
more features, such as state and lifecycle methods.
render() {
Issue Tracker: An issue tracker is a software application that helps teams track and manage issues, bugs,
and tasks throughout the development process. In React, an issue tracker can be built as a web application
that allows users to create, assign, and track issues.
48
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Issue creation : Users can create new issues and assign them to team members.
Issue tracking : Users can track the status of issues and receive updates on their progress.
Issue assignment : Users can assign issues to team members and track their progress.
Prioritization : Users can prioritize issues based on their severity and impact.
Filtering and sorting : Users can filter and sort issues based on various criteria, such as status,
priority, and assignee.
Notifications : Users can receive notifications when issues are updated or assigned to them.
React Classes: React classes are a way to define components using the class keyword. They are used to
create components that have their own state and lifecycle methods.
JavaScript
render() {
State: Class components have their own state, while functional components do not.
49
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Lifecycle methods: Class components have lifecycle methods, such as componentDidMount and
componentWillUnmount, while functional components do not.
This keyword: Class components use the this keyword to refer to the component instance, while functional
components do not.
Class components have several lifecycle methods that are called at different points in the component's life
cycle:
Class components have their own state, which can be updated using the setState method.
constructor(props) {
super(props);
this.state = { count: 0 };
render() {
return (
<div>
<p>Count: {this.state.count}</p>
Increment
</button>
</div>
);
50
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
render() {
Reusability: By breaking down complex components into smaller ones, you can reuse them in other
parts of your application.
Modularity: Composing components helps to keep your code organized and modular, making it easier
to maintain and update.
Flexibility: Composing components allows you to create complex components that can be easily
customized and extended.
// Header.js
function Header() {
// Footer.js
function Footer() {
// App.js
51
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
function App() {
return (
<div>
<Header />
<Footer />
</div>
);
You can also compose components by passing props from a parent component to a child component.
// Button.js
function Button(props) {
// App.js
function App() {
return (
<div>
</div>
);
52
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
used to pass data from a parent component to a child component. Props are immutable,
meaning they cannot be changed once they are passed to a child component.
To pass props, you can add attributes to the child component when you use it in the parent
component.
JavaScript
// Parent component
function Parent() {
return (
<div>
</div>
);
// Child component
function Child(props) {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
53
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
</div>
);
}
Passing Data Using Children,: The children prop is a special prop in React that allows you to pass data from
a parent component to a child component. It is an array of React elements that are passed as children to a
component.
To pass data using children, you can wrap the child component in the parent component and pass the data
as a child element.
// Parent component
function Parent(props) {
return (
<div>
{props.children}
</div>
);
// Child component
function Child() {
54
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
function App() {
return (
<Parent>
<Child />
</Parent>
);
You can pass multiple children to a component by wrapping multiple child elements in the parent
component.
// Parent component
function Parent(props) {
return (
<div>
{props.children}
</div>
);
// Child components
function Child1() {
function Child2() {
55
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
function App() {
return (
<Parent>
<Child1 />
<Child2 />
</Parent>
);
You can access the children of a component using the props.children property.
JavaScript
// Parent component
function Parent(props) {
return (
<div>
<div key={child.key}>{child}</div>
))}
</div>
);
56
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
Dynamic Composition:
Dynamic composition is a technique in React where you can render different components or
elements based on certain conditions or user interactions. This allows you to create more flexible
and reusable components.
To Achieve Dynamic Composition
To achieve dynamic composition in React, you can use the following techniques:
Conditional rendering: Use conditional statements to render different components or
elements based on certain conditions.
Dynamic component rendering: Use dynamic component rendering to render different
components based on user interactions or other conditions.
Higher-order components: Use higher-order components to wrap other components and
provide additional functionality.
Example of Dynamic Composition
Here's an example of dynamic composition in React:
import React, { useState } from 'react';
function DynamicComponent() {
const [showComponent1, setShowComponent1] = useState(true);
return (
<div>
{showComponent1 ? <Component1 /> : <Component2 />}
<button onClick={() => setShowComponent1(!showComponent1)}>Toggle</button>
</div>
);
}
function Component1() {
return <p>This is component 1</p>;
}
function Component2() {
return <p>This is component 2</p>;
}
57
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
function Component1() {
return <p>This is component 1</p>;
}
function Component2() {
return <p>This is component 2</p>;
}
Higher-Order Components
Higher-order components are a technique where you wrap other components and provide additional
functionality.
import React from 'react';
function withLogger(WrappedComponent) {
return function EnhancedComponent(props) {
console.log('Component rendered');
return <WrappedComponent {...props} />;
};
58
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)
}
function Component1() {
return <p>This is component 1</p>;
}
const EnhancedComponent1 = withLogger(Component1);
Module-4:
React State: Initial State, Async State Initialization, Updating State, Lifting State Up, Event Handling,
Stateless Components, Designing Components, State vs. Props, Component Hierarchy, Communication,
Stateless Components. Express, REST API, GraphQL, Field Specification, Graph Based, Single Endpoint,
Strongly Typed, Introspection, Libraries, The About API GraphQL Schema File, The List API, List API
Integration, Custom Scalar types, The Create API, Create API Integration, Query Variables, Input
Validations, Displaying Errors.
59
Dept. CSE, GCE -SJS-