FSD - Unit 1 Part 1
FSD - Unit 1 Part 1
• If client-side scripting language JavaScript is used then, this can be done without
consulting the server
Why Javascript?
Where to write Javascript?
JavaScript code can be embedded within the HTML page or can be written
in an external file.
There are three ways of writing JavaScript depending on the platform:
o Inline/Internal Scripting
o External Scripting
When JavaScript code are written within the HTML file itself, it is called
internal scripting.
Internal scripting, is done with the help of HTML tag : <script> </script>
This tag can be placed either in the head tag or body tag within the HTML
file.
Sample code Javascript
• JavaScript code written inside <head> element is as shown below :
<html>
<head>
<script>
//internal script
</script>
</head>
<body>
</body>
</html>
• JavaScript code can be written in an external file also. The file containing JavaScript code is
saved with the extension *.js (e.g. fileName.js)
• To include the external JavaScript file, the script tag is used with attribute 'src' as shown in
the below-given code-snippet:
<html>
<head>
<!-- *.js file contain the JavaScript code -->
<script src="*.js"></script>
</head>
<body>
Demo.html :-
</body>
</html> <html>
<head>
Demo.js :
<script src="Demo.js"></script>
let firstName="Rexha"; </head>
let lastName ="Bebe"; <body>
</body>
console.log(firstName+" "+lastName);
</html>
Identifiers
• Identifiers should follow the following:
The first character of an identifier should be letters of the alphabet or an
underscore (_) or dollar sign ($).
Subsequent characters can be letters of alphabets or digits or underscores (_)
or a dollar sign ($).
Identifiers are case-sensitive. Hence, firstName and FirstName are not the
same.
Reserved keywords are part of programming language syntax and cannot be used
as identifiers.
Types of Identifiers
An identifier declared using ‘let’ keyword has a block scope i.e., it is available only
within the block in which it is defined.
The value assigned to the identifier can be done either at the time of declaration or
later in the code and can also be altered further.
All the identifiers known so far vary in their scope and with respect to the data it
holds.
let firstName="William";
Example: myScript.js console.log("Welcome to JS course, Mr."+ firstName);
const
const pi = 3.14;
let nr2 = 4;
nr2--;
console.log(nr2);
Quiz
1. What data type is the following variable?
const c = "5";
2. What data type is the following variable?
const c = 91; 3.
3. Which one is generally better, line 1 or line 2?
let empty1 = undefined; //line 1
let empty2 = null; //line 2
4. What is the console output for the following?
let a = "Hello";
a = "world"; console.log(a);
Quiz
5. What will be logged to the console?
let a = "world";
let b = `Hello ${a}!`;
console.log(b);
6. What is the value of a?
let a = "Hello";
a = prompt("world");
console.log(a);
Quiz
7. What is the value of b output to the console?
let a = 5;
let b = 70;
let c = "5";
b++;
console.log(b);
8. What is the value of result?
let result = 3 + 4 * 2 / 8;
Quiz
9. What is the value of total and total2?
let firstNum = 5;
let secondNum = 10;
firstNum++;
secondNum--;
let total = ++firstNum + secondNum;
console.log(total);
let total2 = 500 + 100 / 5 + total--;
console.log(total2);
Quiz
10. What is logged to the console here?
const a = 5;
const b = 10;
console.log(a > 0 && b > 0);
console.log(a == 5 && b == 4);
console.log(true ||false);
console.log(a == 3 || b == 10);
console.log(a == 3 || b == 7);
Statements
• Statements are instructions in JavaScript that have to be executed
by a web browser. JavaScript code is made up of a sequence of
statements and is executed in the same order as they are written.
• A Variable declaration is the simplest example of a JavaScript
statement.
• Syntax: var firstName = "Newton" ;
• Other types of JavaScript statements include conditions/decision-
making, loops, etc.
• White (blank) spaces in statements are ignored.
• It is optional to end each JavaScript statement with a semicolon. But
it is highly recommended to use it as it avoids possible
misinterpretation of the end of the statements by JavaScript engine.
Expression
Statements types
Conditional statements
• Conditional statements help you to decide based on
certain conditions.
• These conditions are specified by a set of conditional
statements having boolean expressions that are
evaluated to a boolean value true or false.
Example
let workingHours = 9.20;
let additionalHours;
(workingHours > 9.15) ? additionalHours = "You have positive
additional hours" : additionalHours = "You have negative
additional hours";
console.log(additionalHours);
Switch statement
The Switch statement is used to select and evaluate one of the many blocks of
code.
Syntax:
switch (expression) {
case value1: code block;
break;
case value2: code block;
break;
case valueN: code block;
break;
default: code block;
}
• Non-Conditional statements are those
statements that do not need any condition to
Non-conditional control the program execution flow.
statements • In JavaScript, it can be broadly classified into
three categories as follows:
Example – switch statement
var perfRating = 5;
switch (perfRating) {
case 5: case 2:
console.log("Very Poor"); console.log("Commendable");
break; break;
case 4: case 1:
console.log("Needs Improvement"); console.log("Outstanding");
break;
break;
default:
case 3: console.log("Sorry!! Invalid Rating.");
console.log("Met Expectations"); }
break;
Non-conditional statements -break
While iterating over the block of code getting executed within the loop, the loop may be required to
be exited if certain condition is met.
The 'break' statement is used to terminate the loop and transfer control to the first statement
following the loop.
Below example shows for loop with five iterations which increment variable "counter".
When loop counter = 3, loop terminates.
Also, shown below is the value of the counter and loopVar for every iteration of the loop.
• var counter = 0;
• for (var loop = 0; loop < 5; loop++) {
• if (loop == 3) loopVar counter
• break; 0 1
1 2
• counter++;
2 3
• } 3 Loop terminated. counter = 3.
Non-conditional statements -
continue
Continue statement is used to terminate the current iteration of the loop and continue
execution of the loop with the next iteration.
Below example shows for loop with five iterations which increment variable "counter".
When loop counter = 3, the current iteration is skipped and moved to the next iteration.
Also, shown below is the value of the counter and the variable loop for every iteration of
the loop.
loopVar counter
• var counter = 0; 0 1
• for (var loop = 0; loop < 5; loop++) { 1 2
• if (loop == 3) 2 3
Iteration terminated. Hence counter is
• continue; 3
not incremented.
• counter++; 4 4
• }
Comments
• Comments in JavaScript can be used to prevent the
execution of a certain lines of code and to
add information in the code that explains the
significance of the line of code being written.
• JavaScript supports two kinds of comments.
Exercise
Write a JavaScript code to make online booking of theatre tickets and calculate the total price based
on the below conditions:
• If seats to be booked are not more than 2, the cost per ticket remains $9.
• If seats are 5 or more, booking is not allowed.
• If seats to be booked are more than 2 but less than 5, based on the number of seats booked, do the
following:
o Calculate total cost by applying discounts of 5, 7, 9, 11 percent, and so on for customer 1,2,3
and 4.
o Try the code with different values for the number of seats.
Loops
for loop
• 'for' loop is used when the block of code is expected to
execute for a specific number of times. To implement it,
use the following syntax.
let counter = 0;
for (let loopVar = 0; loopVar < 5; loopVar++) {
counter = counter + 1;
console.log(counter);
}
while loop
• while' loop is used when the block of code is to be executed as long
as the specified condition is true.
let counter = 0;
let loopVar = 0;
while (loopVar < 5) {
console.log(loopVar);
counter++;
loopVar++;
console.log(counter);
}
do-while loop
let counter = 0;
let loopVar = 0;
do {
console.log(loopVar);
counter++;
loopVar++;
console.log(counter);
}
while (loopVar < 5);
Quiz
1. What will be outputted to the console in this instance?
const q = '1';
switch (q) {
case '1’: answer = "one"; break;
case 1: answer = 1; break;
case 2: answer = "this is the one"; break;
default: answer = "not working";
}
console.log(answer);
Quiz
2. What will be outputted to the console in this instance?
const q = 1;
switch (q)
{
case '1': answer = "one";
case 1: answer = 1;
case 2: answer = "this is the one"; break;
default: answer = "not working";
} console.log(answer);
Quiz
3. What will be outputted to the console in this instance?
let login = false;
let outputHolder = "";
let userOkay = login ? outputHolder = "logout" :
outputHolder = "login";
console.log(userOkay);
Quiz
4. What will be outputted to the console in this instance?
const userNames = ["Mike", "John", "Larry"];
const userInput = "John";
let htmlOutput = "";
if (userNames.indexOf(userInput) > -1)
{ htmlOutput = "Welcome, that is a user"; }
else { htmlOutput = "Denied, not a user "; }
console.log(htmlOutput + ": " + userInput);
Array in JS
• JavaScript Array is a data structure that allows you to
store and organize multiple values within a single
variable.
• It is a versatile and dynamic object.
• It can hold various data types, including numbers,
strings, objects, and even other arrays.
• Arrays in JavaScript are zero-indexed i.e. the first
element is accessed with an index 0, the second
element with an index of 1, and so forth
Arrays
let activity =
company.activities[1]; -> ??
Objects in arrays
This function parses string and returns a float number. parseFloat("10.34"); //10.34
The method stops parsing when it encounters a non-numerical character parseFloat("10 20 30"); //10
parseFloat
and further characters are ignored.
() parseFloat("10.50 years"); //10.50
It returns NaN when the first non-whitespace character cannot be
converted to number.
eval("let num1=2; let
It takes an argument of type string which can be an expression,
eval() num2=3;let result= num1 *
statement or sequence of statements and evaluates them.
num2;console.log(result)");
Built-in functions Description
It executes a given function after waiting for the specified number of milliseconds.
setTimeout() It takes 2 parameters. First is the function to be executed and the second is the
number of milliseconds after which the given function should be executed.
clearTimeout() It takes the parameter "timeoutID" which is the identifier of the timeout that can
be used to cancel the execution of setTimeout(). The ID is returned by the
setTimeout().
It executes the given function repetitively.
setInterval() It takes 2 parameters, first is the function to be executed and second is the
number of milliseconds. The function executes continuously after every given
number of milliseconds.
• The next() method is used to resume execution and retrieve the next
value.
• The done property indicates whether the generator has finished
executing.
• The yield operator is used to pause and resume a generator function.
Example
function* myGenerator() {
yield “Sona”;
Guess the
yield 2; Output?
yield “Tech”;
}
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
console.log(gen.next().value); // undefined (no more yields)
for loop – generator function
function* numbers()
{ Guess the
Output?
yield 10;
yield 20;
yield 30;
}
for (const num of numbers())
{ console.log(num); // 10, 20, 30 }
Generator methods
Method Description
next() Returns a value of yield
Returns a value and terminates
return()
the generator
Throws an error and terminates
throw()
the generator
JavaScript return Vs yield Keyword
} }, };
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello
World!";
</script>
</body>
</html>
Select elements in the document
• getElementById() – select an element by id.
• getElementsByName() – select elements by name.
• getElementsByTagName() – select elements by a tag name.
• getElementsByClassName() – select elements by one or more
class names.
• querySelector() –to select the first element that matches the
query.
• querySelectorAll() - select all the elements that match the
query
• innerHTML - getting or replacing the content of HTML elements.
Example DOM tree
<!DOCTYPE html>
<html>
<body>
<h2>Finding HTML Elements Using document.images</h2>
<img src="pic_htmltree.gif" width="486" height="266"> Guess the
<img src="pic_navigate.gif" width="362" height="255">Output?
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Number of images: " + document.images.length;
</script>
</body>
</html> Ref : https://www.w3schools.com/js/tryit.asp?
filename=tryjs_doc_images
Example
<h1>JavaScript getElementsByTagName() Demo</h1>
<h2>First heading</h2>
<p>This is the first paragraph.</p>
<h2>Second heading</h2> Guess the
Output?
<p>This is the second paragraph.</p>
<h2>Third heading</h2>
<p>This is the third paragraph.</p>
<script>
let headings = document.getElementsByTagName('h2');
console.log(`The number of H2 tags: ${headings.length}`);
</script>
Browser events
HTML events
• An HTML event can be something the browser does, or something a user
does.
• An event is a signal that something has happened.
• All DOM nodes generate such signals (but events are not limited to DOM).
• Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
• Often, when events happen, you may want to do something.
• JavaScript lets you execute code when events are detected.
• HTML allows event handler attributes, with JavaScript code, to be added
to HTML elements.
Interactive content
• Interactive content is content that responds to the actions of
a user.
• For example, of a web app in which you can create postcards
dynamically, or play a game on a website in a web browser.
• This interactive content is made possible by changing the
DOM based on user interactions.
• These interactions could be anything: entering text in an
input field, clicking somewhere on the page, hovering over a
certain element with the mouse, or a certain input with the
keyboard.
• All these are called events.
Specifying events
• There are three ways to specify events.
• Specifying events with HTML
• <p id="unique" onclick="magic()">Click here for magic!
</p>
• Specifying events with JavaScript
• document.getElementById("unique").onclick = function()
{ magic(); };
• Specifying events with event listeners
• document.getElementById("unique").addEventListener("click",
magic);
• document.getElementById("unique").addEventListener("click",
function() { magic(arg1, arg2) });
Mouse events
• ondblclick: when the mouse is double-clicked
• onmousedown: when the mouse clicks on top of an element
without the click being released
• onmouseup: when the mouse click on top of an element is
released
• onmouseenter: when the mouse moves onto an element
• onmouseleave: when the mouse leaves an element and all of its
children
• onmousemove: when the mouse moves over an element
• onmouseout: when the mouse leaves an individual element
• onmouseover: when the mouse hovers over an element
Keyboard events
• keydown and keyup – when a keyboard key is pressed
and released.
CSS events
• submit – when the visitor submits a <form>.
Unit 1 – Javascript and Basics of
MERN Stack
JavaScript Fundamentals – Objects – Generators,
advanced iteration – modules – DOM tree – Node
properties – browser events – Event delegation – UI
Events – Forms, controls – Document and resource
loading – Mutation observer – Event loop: micro-tasks
and macro-tasks – MERN Components – React – Node.js –
Express – MongoDB – Need for MERN – Server – Less
Hello World – Server Setup – nvm – Node.js - npm
Event delegation
Event bubbling
• Event bubbling in JavaScript is a mechanism where an event triggered
on a child element propagates upward through its ancestors in the
DOM.
• Event Listeners: If multiple event listeners are attached in the bubbling phase,
they are executed in sequence, starting from the innermost target element.
Event bubbling and capturing
• Bubbling - When an event happens on a component, it
first runs the event handler on it, then on its parent
component, then all the way up on other ancestors’
components. By default, all event handles through this
order from center component event to outermost
component event.
• Capturing - The event handler is first on its parent
component and then on the component where it was
actually wanted to fire that event handler. In short, it
means that the event is first captured by the outermost
element and propagated to the inner elements. It is also
called trickle down.
Event bubbling and capturing
<!DOCTYPE html> <script>
<html>
function showMessage(event) {
<body>
<style> alert(`Clicked: ${this.id}`);
Exampl div { }
e
border: 2px solid black;
padding: 20px;
document.getElementById("outer").addEventList
margin: 10px;
ener("click", showMessage);
cursor: pointer;
}
</style> document.getElementById("middle").addEventLis
<div id="outer"> tener("click", showMessage);
Outer Div
<div id="middle"> document.getElementById("inner").addEventListe
Middle Div ner("click", showMessage);
<div id="inner">
</script>
Inner Div (Click me)
</div> </body>
</div> </html>
</div>
Event delegation
• Event Delegation is basically a pattern to handle events efficiently.
• Instead of adding an event listener to each and every similar element,
we can add an event listener to a parent element and call an event on
a particular target using the .target property of the event object.
• Example
const div = document.getElementsByTagName("div")[0]
div.addEventListener("click", (event) => {
if(event.target.tagName == 'BUTTON') {
console.log("button was clicked")
}
})
Event delegation
document.getElementById("btn1").addEventListener("click", () => alert("Button 1 clicked"));
document.getElementById("btn2").addEventListener("click", () => alert("Button 2 clicked"));
document.getElementById("btn3").addEventListener("click", () => alert("Button 3 clicked"));
document.getElementById("button-
container").addEventListener("click", function(event) {
if (event.target.tagName === "BUTTON") {
alert(`${event.target.textContent} clicked`);
}
});
<html lang="en">
<body>
<head>
<h2>Event Delegation Example</h2>
<meta charset="UTF-8"> <div id="button-container">
<meta name="viewport" <button>Button 1</button>
ampl
content="width=device-width, initial-
scale=1.0">
<button>Button 2</button>
<button>Button 3</button>
<title>Event Delegation
Example</title> </div>
#button-container { <script>
<style>
margin: 20px; document.getElementById("button-
body { padding: 10px; container").addEventListener("click", function(ev
font-family: Arial, sans-serif;border: 2px solid #333;if (event.target.tagName === "BUTTON"
text-align: center; display: inline-block; alert(`${event.target.textContent} clic
} }
margin-top: 50px;
button {
});
} margin: 5px;
</script>
padding: 10px;
</body>
font-size: 16px;
</html>
cursor: pointer;
}
</style>
UI events and
forms
UI events
• UI events – occur when a user interacts with the
browser’s user interface (UI) – work with window object
Forms
• A form is a container/holder • The HTML <form> element can contain
that can hold several elements. one or more of the following form
elements:
• In JavaScript, the concept of
forms is used to collect user’s 1. <input>
input using different elements 2. <label>
such as input fields, buttons, 3. <select>
labels, fieldsets, text fields, and 4. <textarea>
so on. 5. <button>
6. <fieldset>
• JavaScript can be used to 7. <legend>
interact with the forms, to 8. <datalist>
validate the forms, to process 9. <output>
the forms, etc. 10. <option>
11. <optgroup>
Example
<body>
<p id="details"> </p>
<form>
Name: <input type="text" id="name"/>
<br><br>
Age: <input type="text" id="age"/>
<br><br>
<input type="button" value="Show Details" onclick="showDetails()"/>
</form>
<script>
function showDetails(){
var empDetails = document.getElementById('details');
var empName = document.getElementById('name');
var empAge = document.getElementById('age');
empDetails.innerHTML = "Name: " + empName.value + "<br>" + " Age:
" + empAge.value;
}
</script>
</body>
addEventListener()
• The addEventListener() method of the EventTarget interface sets up a
function that will be called whenever the specified event is delivered
to the target.
• addEventListener(type, listener)
• addEventListener(type, listener, options)
• addEventListener(type, listener, useCapture)
• Type - A case-sensitive string representing the event type to listen for.
• Listener - The object that receives a notification (an object that
implements the Event interface) when an event of the specified type
occurs.
• useCapture - A boolean indicating whether the event should be
captured during the capture phase (true) or the bubbling phase (false).
Example addEventListener()
document.getElementById("myButton").addEventListener("click",
function() {
Basic Click Event
alert("Button clicked!");
});
window.addEventListener("load", function() {
console.log("Page and all resources loaded");
});
beforeunload and unload Events
• Fired when a user is leaving the page.
window.addEventListener("beforeunload", function(event)
{
event.preventDefault();
event.returnValue = "Are you sure you want to
leave?";
});
event.preventDefault()
• The event.preventDefault() method prevents the default
behavior of an event from occurring.
• It is commonly used to stop actions like form
submission, link navigation, and right-click context
menus.
Mutation observer
Mutation Observer
• Mutation Observer is a Web API provided by modern
browsers for detecting changes in the DOM.
• Using Mutation Observer, when something in the DOM
changes, we can invoke a callback function to react to
those changes.
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
1. callback – A function executed when mutations are
detected.
2. targetNode – The DOM element to observe.
3. config – An object specifying the types of mutations to
How does it works? Step 1
• Create MutationObserver instance by passing it a function that
would be called every time a mutation has occurred.
• The first argument (i.e “mutations”) of the function is a
collection of all mutations which have occurred in a single batch.
• Each mutation provides information about its type and the
changes which have occurred.
var mutationObserver = new
MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation);
});
});
How does it works? Step 2
• Use observe() method to start observing the DOM
changes. The targetNode is the root of the subtree of
nodes to monitor for changes.
• The observerOptions parameter contains properties we
want to observe eg. childList, attributes..etc.var
mutationObserver.observe(targetNode, observerOptions);
How does it works? Step 3
mutationObserver.disconnect();
Mutation Observer - Options
• childList: It is used to observe the mutation in the target node’s child
elements.
• attributes: It is used to observe the mutation of the target node’s attributes.
• characterData: It is used to observe the mutation of the target node’s data.
• subtree: It is used to observe the mutation of the target and the target’s
descendants.
• attributeOldValue: It is used to observe the target’s attribute value before
the mutation. It is set to true if the attribute value is set to true.
• characterDataOldValue: It is used to observe the target’s data before the
mutation needs to be recorded. It is set to true if the characterData is set to
true.
• attributeFilter: If not all attribute mutations need not be observed, set the
attributeFilter to an array of attribute local name
Example - Observing Attribute
Changes
• Detect when an attribute (e.g., class, id, style) changes.
<head>
<title>
MutationObserver Example
</title>
<style>
#colorDiv {
width: 100px;
height: 100px;
<body>
Promise.resolve().then(function() {
console.log("Promise"); // microTask! Start
End
}); Promise
Timeout
console.log("End");