IP Final Assginment-15
IP Final Assginment-15
Aim: Develop a web application by using HTML Tags , Elements , Attributes , Head , Body ,
Hyperlinks , Formatting Images , Tables , Lists, Frames ,Forms and Multimedia elements
should be used.
Theory :
HTML TAGS:
1: <!DOCTYPE> :- Is the first tag in HTML document which specifies DTD used by the document. l A
DTD is separate file containing formal definition of grammar used in markup language. l The browser
checks the code of document against the rule in declaration. l Tells the browser about the version of
language. l Does not have a closing tag The declaration helps the browser to display a web page
correctly.
9: <body>: represents the content of an HTML document. There can be only one such
element in a document.
10:<footer>: Represents a footer for its nearest ancestor sectioning content or sectioning
root element. A <footer> typically contains information about the author of the section,
copyright data, or links to related documents.
1: <dd>: Provides the description, definition, or value for the preceding term (<dd>)
in a description list (<dl>).
2: <div>: The generic container for flow content. It has no effect on the content or
layout until styled in some way using CSS (e.g., styling is directly applied to it, or
some kind of layout model like flexbox is applied to its parent element).
3: <dl>: Represents a description list. The element encloses a list of groups of
terms (specified using the <dt> element) and descriptions (provided
by <dd> elements). Common uses for this element are to implement a glossary or
to display metadata (a list of key-value pairs).
4:<dt>: Specifies a term in a description or definition list, and as such must be
used inside a <dl> element. It is usually followed by a <dd> element; however,
multiple <dt> elements in a row indicate several terms that are all defined by the
immediate next <dd> element.
1: <a>:
Together with its href attribute, creates a hyperlink to web pages, files, email
addresses, locations within the current page, or anything else a URL can address.
3: <i>: Represents a range of text that is set off from the normal text for some
reason, such as idiomatic text, technical terms, and taxonomical designations,
among others. Historically, these have been presented using italicized type, which
is the original source of the <i> naming of this element.
IMAGES AND MULTIMEDIA:
3:< video>: Embeds a media player which supports video playback into the
document. You can also use <video> for audio content, but the audio element may
provide a more appropriate user experience.
Table Content:
4:<th>: Defines a cell as a header of a group of table cells. The exact nature of
this group is defined by the scope and headers attributes.
5:<tr>: Defines a row of cells in a table. The row's cells can then be established
using a mix of <td> Data cell) and <th> (header cell) elements.
FORMS:
CONCLUSION:
We have created a working website using basic HTML tags, 0Attributes , Head , Body ,
Hyperlinks , Formatting Images , Tables , Lists, Frames ,Forms and Multimedia elements
1: index.html
2: second.html
3:third.html
4:fourth.html
5:fivth.html
OUTPUT:
Aim: Using CSS and CSS3 enhance the web application developed in Assignment #1 Color,
Background, Font, Table, List, CSS3 selectors, Pseudo classes, and Pseudo elements properties
should be used to enhance the web pages.
Theory:
CSS stands for "Cascading Style Sheets." It is a style sheet language used to describe the
presentation and formatting of a document written in markup languages like HTML and XML.
CSS allows web developers to control the layout, colors, fonts, and other visual aspects of a web
page, separating the content from its presentation. The primary purpose of CSS is to provide a way
to style web pages consistently across different devices and browsers. Instead of applying styles
directly to individual HTML elements, CSS allows developers to create style rules that can be
applied to multiple elements at once. This approach promotes a more efficient and maintainable
way of managing the appearance of a website. The "Cascading" part of CSS refers to the way
styles are applied in a specific order. If multiple CSS rules target the same element, the browser
follows a set of rules to determine which style should be applied. This includes considering the
specificity of the selector, the order of appearance in the CSS file, and the use of inline styles or
external stylesheets.
1. Color in CSS:
Color is an essential aspect of web design, and CSS provides various ways to define colors for
elements. Colors can be specified using color names, hexadecimal values (#RRGGBB), RGB
values (rgb(R, G, B)), or HSL values (hsl(H, S%, L%)). CSS allows you to set the color of text,
backgrounds, borders, and other elements, enhancing the visual appeal and readability of a web
page.
2. Background in CSS:
CSS allows you to control the background of elements. You can set background colors,
background images, and control their position and behavior using properties like `background-
color`, `background-image`, `background-position`, `background-repeat`, etc. Backgrounds help
improve the overall look and feel of a web page.
3. Font in CSS:
CSS enables you to customize the font used for text on a web page. You can set the font family,
font size, font weight, font style, and more. By choosing appropriate fonts, you can enhance
readability and create a consistent visual identity for your website.
4. Tables in CSS:
CSS allows you to style HTML tables, making them visually appealing and easier to read. You
can apply styles to the table, table headers (`<th>`), table cells (`<td>`), and control borders,
padding, spacing, background colors, etc.
5. Lists in CSS:
CSS provides options to style HTML lists (ordered and unordered). You can remove default list
styles, change bullet styles, control spacing, and add custom styling to list items.
6. CSS3 Selectors:
CSS3 introduced advanced selectors that allow you to target elements based on more complex
criteria. Examples include attribute selectors (`[attribute=value]`), child selectors (`parent >
child`), sibling selectors (`prev + next`), and more. CSS3 selectors give you greater control and
flexibility in styling specific elements on a web page.
7. Pseudo-classes:
Pseudo-classes are used to define styles for elements in specific states or conditions that cannot
be represented with regular selectors. For example, `:hover` targets an element when the user
hovers over it, `:active` targets an element when it is being clicked, and `:first-child` targets the
first child element of its parent.
8. Pseudo-elements:
Pseudo-elements allow you to style parts of an element's content or add content before or after
an element. Commonly used pseudo-elements are `::before` and `::after`, which add content before
and after an element, respectively.
By leveraging these CSS concepts, web developers can create visually appealing and user-friendly
web pages, improving the overall user experience and design of the website.
Conclusion: In conclusion, using CSS (Cascading Style Sheets) is crucial for modern web
development due to the following reasons:
Separation of Concerns: CSS allows the separation of the presentation layer from the HTML
structure, enabling cleaner and more maintainable code. This separation makes it easier to update
the visual style without affecting the content and structure of the web page.
Consistency and Branding: CSS provides the ability to define consistent styles across a website,
ensuring a unified look and feel. By setting fonts, colors, and layouts consistently, you can
establish a strong brand identity and enhance user recognition.
Responsive Web Design: CSS enables responsive web design, allowing websites to adapt and
display correctly on various devices and screen sizes. Media queries and flexible layouts ensure
that the content is accessible and user-friendly on desktops, tablets, and smartphones.
Enhanced User Experience: Properly styled websites created with CSS provide a more pleasant
and engaging user experience. By improving readability, using appealing colors and
backgrounds, and organizing content effectively, users are more likely to stay on the site and find
what they need.
Efficient Styling and Maintenance: CSS allows you to apply styles to multiple elements
simultaneously, reducing redundancy and making maintenance easier. You can define classes
and IDs to target specific elements and update styles globally with minimal effort.
Optimization and Performance: CSS is lightweight and loads quickly, contributing to improved
website performance. By reducing the need for inline styles and leveraging external stylesheets,
you can optimize the loading speed of your web pages.
Flexibility and Customization: With CSS, you have immense flexibility to customize the
appearance of your website. You can use CSS3 properties, pseudo-classes, and pseudo-elements
to create intricate designs, animations, and interactive effects.
1:index.html: Internal Style sheet
<!DOCTYPE html>
<html>
<head>
<title>Internal CSS Form</title>
<style>
.my-form {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
.my-form label {
display: block;
margin-bottom: 5px;
}
.my-form input[type="text"],
.my-form input[type="email"],
.my-form textarea {
width: 100%;
padding: 5px;
margin-bottom: 10px;
}
.my-form input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<form class="my-form">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
<div>
<input type="radio" name="radioelement" id="option1" value="M" />
<label for="option1">Male</label>
<input type="radio" name="radioelement" id="option2" value="F" />
<label for="option2">Female</label>
</div>
<div>
<input type="checkbox" id="cb1" name="cb1" value="1" />
<label for="cb1">Checkbox 1</label>
<br />
<br />
<br />
<br />
<br />
<!-- range element -->
<div>
<label for="Range">Select a range :</label>
<input type="range" name="range" id="range" />
</div>
<br />
<!-- number element -->
<div>
<label for="Number">Choose a number :</label>
<input type="number" name="number" id="number" />
</div>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4"></textarea>
<nav class="navbar">
<ul>
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Contact</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Design</a></li>
</ul>
</nav>
<!-- main section -->
<div class="main">
<!-- main title -->
<div class="left">
<!-- left side div -->
<h3>The 28 best skincare products of 2021</h3>
<p class="anc">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Animi,
temporibus? Lorem ipsum dolor sit amet consectetur adipisicing elit.
Perferendis, adipisci inventore nemo neque architecto quis minima
quidem eligendi sint minus officiis dolorum soluta. Corporis ea
praesentium pariatur iusto ratione laborum!
</p>
<br />
<p class="anc">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aut
excepturi saepe dicta, eius placeat repellendus nihil suscipit
reiciendis deserunt quisquam.
</p>
<br />
<p class="anc">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore
soluta corrupti et, architecto quis corporis accusamus consectetur,
nesciunt dolorum quae voluptates cupiditate nulla. Similique,
deserunt! Architecto, officia est, eveniet totam voluptatem, veniam
aliquid culpa expedita nihil nulla recusandae nam aliquam.
</p>
<!-- left side ends -->
</div><div class="right">
<!-- right side div image part -->
<img src="Images/premium_photo-1690297971162-5fe7ddf2c48d.avif" alt="Heelo" />
</div>
<!-- right side ends -->
</div>
<!-- main title ends -->
<!-- main section ends -->
<div>
NOW Let's learn Inline style sheet
<a href="third.html">Click here</a>
</div>
</body>
</html>
Style.css
h4 {
color: blueviolet ;
background-color: blanchedalmond;
}
/* class has to start with . */
/* but p hum sida element selector se kiya */
/* class selector */
.text-warning{
color: rgb(255, 94, 0);
}
/* id selector */
#foo {
font-size: 40px;
background-color: turquoise;
color: black;
}
.ext{
background-color: black;
color: aqua;
}
/* Priority wise 1:inline
2:internal
3:external */
/* reset style */
* {
margin: 0;
padding: 0;
font-family: 'Teko', sans-serif;
}
/* reset style ends */
body{
background-color: #819fbb;
/* height: 180px; */
.anc{
line-height: 20px;
}
}
/* nav bar section ends */
.left ,.right{
display: inline-block;
width: 50%;
vertical-align: top;
}
img{
width: 100%;
border-radius: 10px;
height: calc(100vh - 100px);
position: relative;
bottom: 50px;
.main{
margin: 15px 50px;
background-color: #f5ebd3;
padding: 30px;
border-radius: 5px;
/* height: calc(100vh - 100px); */
}
h1{
margin: 10px;
padding-left: 30px;
}
3:third.html
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS Form</title>
</head>
<body>
<form style="max-width: 400px; margin: 0 auto; padding: 20px; border: 1px solid #ccc;
border-radius: 5px; background-color: aqua;">
<label for="name">Name:</label>
<input type="text" id="name" name="name" style="width: 100%; padding: 5px; margin-
bottom: 10px;">
<label for="email">Email:</label>
<input type="email" id="email" name="email" style="width: 100%; padding: 5px;
margin-bottom: 10px;">
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" style="width: 100%; padding: 5px;
margin-bottom: 10px;"></textarea>
OUTPUT:
Index.html
Second.html
Third.html
LAB ASSIGNMENT -03
AIM: Create a Website Using BootStrap.
Theory:
• Containers center and horizontally pad your content. Use .container for a responsive
pixel width, .container-fluid for width: 100% across all viewports and devices, or a
responsive container (e.g., .container-md) for a combination of fluid and pixel widths.
• Rows are wrappers for columns. Each column has horizontal padding (called a gutter)
for controlling the space between them. This padding is then counteracted on the rows
with negative margins to ensure the content in your columns is visually aligned down the
left side. Rows also support modifier classes to uniformly apply column sizing and gutter
classes to change the spacing of your content.
• Columns are incredibly flexible. There are 12 template columns available per row,
allowing you to create different combinations of elements that span any number of
columns. Column classes indicate the number of template columns to span (e.g., col-
4 spans four). widths are set in percentages so you always have the same relative sizing
• Grid System: Bootstrap's grid system allows developers to create responsive layouts by dividing
the screen into a 12-column grid. This makes it easy to arrange content in different configurations
based on screen size.
Navbar:
• Navbars and their contents are fluid by default. Change the container to
limit their horizontal width in different ways.
• Use our spacing and flex utility classes for controlling spacing and
alignment within navbars.
• Navbars are responsive by default, but you can easily modify them to
change that. Responsive behavior depends on our Collapse JavaScript
plugin.
• Ensure accessibility by using a <nav> element or, if using a more generic
element such as a <div>, add a role="navigation" to every navbar to explicitly
identify it as a landmark region for users of assistive technologies.
• Indicate the current item by using aria-current="page" for the current page
or aria-current="true" for the current item in a set.
The Bootstrap navigation bar component allows developers to create responsive and
customizable navigation menus, complete with dropdowns, branding, and mobile
responsiveness.
Forms:
Bootstrap’s form controls expand on our Rebooted form styles with classes. Use these
classes to opt into their customized displays for a more consistent rendering across
browsers and devices.
Be sure to use an appropriate type attribute on all inputs (e.g., email for email address
or number for numerical information) to take advantage of newer input controls like
email verification, number selection, and more.
Bootstrap offers pre-styled form elements like input fields, checkboxes, radio buttons,
dropdowns, and more, making it easier to create aesthetically pleasing and consistent
forms.
Typography: Bootstrap offers a set of typography styles, including headings, paragraphs,
lists, and more, with consistent and visually pleasing typography across different devices.
Buttons: Bootstrap provides styles for creating various types of buttons, such as primary,
secondary, success, danger, and more, along with different sizes and styles..
Cards: Cards are versatile content containers that can hold various types of content, such
as text, images, and buttons. They're often used to display blocks of content in an
organized manner.
Alerts: Bootstrap provides styled alerts for conveying different types of messages or
notifications to users.
Modal Dialogs: Modal dialogs are pop-up windows that overlay the main content and are
used for displaying additional information or actions without navigating away from the
current page.
Carousel: Bootstrap's carousel component enables the creation of image sliders and
carousels for showcasing multiple images or pieces of content.
Icons: Bootstrap includes an icon library (formerly Glyphicons) that provides a set of
scalable vector icons that can be easily integrated into your design.
Utilities: Bootstrap also offers a variety of utility classes that help with spacing,
alignment, display properties, and more.
LAB OUTCOME:
LO3: Construct a responsive website using Bootstrap.
CONCLUSION:
Bootstrap stands as a foundational cornerstone in contemporary web development, offering a
comprehensive toolkit of pre-designed elements that empower developers to create responsive, visually
appealing, and user-friendly websites and applications. Through its versatile grid system, extensive
typography options, pre-styled components, and customizable features, Bootstrap streamlines the
development process while ensuring consistency and responsiveness across various devices and screen
sizes. Its robust framework not only accelerates the creation of sophisticated interfaces but also
encourages best practices in design and layout.0.
1:index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Website using pure bootstrap</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-
9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM"
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
integrity="sha512-
iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==
"
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
</head>
<body>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-
geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz"
crossorigin="anonymous"
defer
></script>
</li> -->
<li class="nav-item">
<a class="nav-link active mx-3 text-uppercase" aria-current="page"
href="#hero" style="color: white; ">Home</a>
</li>
<li class="nav-item">
<a class="nav-link mx-3 text-uppercase" href="#skills" style="color:
white;">Skills</a>
</li>
</div>
</form>
</div>
</nav>
<!-- navbar section ends -->
<section id="hero">
<div class="container-fluid ">
<div
class="row align-items-center justify-content-center bg-info"
style="height: 100vh"
>
<div class="col-md-10 text-center">
<p class="display-3">
<span class="text-warning text-capitalize">pure bootstrap</span>
<span class="text-white fw-bold">Website</span>
</p>
</p>
<p class="btn btn-outline-warning">Learn more</p>
<!-- <a class="btn btn-outline-warning"></a>remove href href="" while using a
as button -->
</div>
<div class="col-lg-4 col-md-10 col-10">
<i class="fa-solid fa-pen-to-square fa-6x text-warning"></i>
<h1 class="text-secondary">Design</h1>
<p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing
elit. Omnis, mollitia.</p>
<p class="btn btn-outline-warning">Learn more</p>
</div>
<div class="col-lg-4 col-md-10 col-10">
<i class="fa-solid fa-gears fa-6x text-warning"></i>
<h1 class="text-secondary">Creativity</h1>
<p class="text-muted">Lorem ipsum dolor sit amet consectetur adipisicing elit.
Suscipit, nisi.</p>
<p class="btn btn-outline-warning">Learn more</p>
</div>
</div>
</section>
<!-- skills section ends -->
</div>
</section>
<!-- project section ends -->
</div>
</section>
<!-- Team section ends -->
<!-- progress section starts -->
<section class="container-fluid">
<div class="row text-center py-2 fw-bold ">
<div class="col">
<div>
<p class="display-3 text-warning text-capitalize">Progress</p>
</div>
</div>
</div>
<div class="mb-3">
<label for="comment1">Comments:</label>
<textarea class="form-control" placeholder="Leave a comment here"
id="comment1" style="height: 100px"></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-warning w-100">Submit</button>
</div>
</form>
</div>
</div>
</section>
<!-- contact us ends -->
OUTPUT:
LAB ASSIGNMENT -4A
AIM: Implement various Operations such as Conditional , Loops , Functions.
LAB OUTCOME:
LO4: Use JavaScript to perform various Operations.
THEORY:
FUNCTION:
• Functions are the building blocks of readable, maintainable, and reusable code.
• Functions are defined using the function keyword.
• To force execution of the function, it must be called.
• This is called as function invocation
Classification of function:
1. Returning:
• Functions may also return the value along with control, back to the caller.
• Such functions are called as returning functions.
• A returning function must end with a return statement.
• A function can return at the most one value. In other words, there can be only
one return statement per function.
• The return statement should be the last statement in the function
2. Parametrized
• Parameters are a mechanism to pass values to functions.
• Parameters form a part of the function’s signature.
• The parameter values are passed to the function during its invocation.
• Unless explicitly specified, the number of values passed to a function must match
the number of parameters defined
3.Default Function Parameter :
• In ES6, a function allows the parameters to be initialized with default values, if no
values are passed to it or it is undefined.
4 • Rest Parameters:
• Rest parameters are similar to variable arguments in Java.
• Rest parameters doesn’t restrict the number of values that you can pass to a
function.
• To declare a rest parameter, the parameter name is prefixed with three periods,
known as the spread operator.
• A rest parameter allows you to represent an indefinite number of arguments as
an array.
5.Anonymous Function :
• Functions that are not bound to an identifier (function name) are called as
anonymous functions.
• These functions are dynamically declared at runtime.
• Anonymous functions can accept inputs and return outputs, just as standard
functions do.
• An anonymous function is usually not accessible after its initial creation.
• Variables can be assigned an anonymous function.
• Such an expression is called a function expression
6.Lambda Function/ Arrow Function
• refers to anonymous functions in programming.
• Lambda functions are a concise mechanism to represent anonymous functions.
• These functions are also called as Arrow functions.
• There are 3 parts to a Lambda function –
• Parameters − A function may optionally have parameters.
• The fat arrow notation/lambda notation (=>): It is also called as the goes to operator.
• Statements − Represents the function’s instruction set. ([param1, parma2,…param n]
)=>statement;
Loops:
• Certain instructions require repeated execution.
• Loops are an ideal way to do the same.
• A loop represents a set of instructions that must be repeated.
• Definite Loop:
• A loop whose number of iterations are definite/fixed is termed as a definite loop.
• The ‘for loop’ is an implementation of a definite loop
Classification of loop:
1.For Loops:
For loops are commonly used when you know the number of iterations you want to
perform. They consist of three parts: initialization, condition, and increment (or
decrement). For each iteration, the condition is evaluated, and if it's true, the loop body is
executed.
2.While Loops:
While loops are used when you want to repeatedly execute a block of code as long as a
specified condition is true. The condition is checked before each iteration, and if it's true,
the loop body is executed.
3.forof: loop, which is specifically designed for iterating over values in arrays, strings,
maps, sets, and other iterable objects, and the
4.forEach method, which is available on arrays for iterating through their elements.
5.do-while:
The condition is checked after the loop body is executed. This means that the loop body
will always execute at least once, regardless of whether the condition is initially true or
false.
Conditional Statement:
Conditional statements in web development are used to make decisions based on certain
conditions. They allow your code to execute different blocks of code depending on
whether a specified condition is true or false. Conditional statements are essential for
creating dynamic and interactive web applications. The most common types of
conditional statements are:
2. if-else Statement: The if-else statement is used to execute one block of code if a
condition is true and another block of code if the condition is false.
3. if-else if-else Statement: This is an extension of the if-else statement that allows
you to test multiple conditions and execute corresponding blocks of code.
These conditional statements allow you to control the flow of your code based on
different conditions, enabling you to create responsive and interactive web applications.
They are often used in combination with loops, functions, and other programming
constructs to achieve more complex behavior in your web development projects.
CONCULSION:
We have Studied Various operation on Function , Loops and Conditional Statement.
FUNCTIONS:
LOOPS:
CONDITIONAL:
Write a JavaScript code to change the background color of the web page
automatically after every 5 second.
LAB ASSGINMENT – 4B
Aim: Write a program on inheritance, iterators and generators.
Lab Outcome:
LO4- Use JavaScript to develop interactive web Pages.
Theory:
Iterators in JavaScript:
An iterator is an object that allows you to traverse or iterate through a
collection of data, such as an array or an object. In JavaScript, iterators are
typically used with iterable data structures like arrays, strings, and objects.
Iterators provide a standardized way to access elements in a sequence, one at a
time, and they work with the for...of loop and other looping constructs.
Iterators are defined by two methods:
next(): This method returns an object with two properties: value (the current
element in the iteration) and done (a boolean indicating whether the iteration
is complete).
Symbol.iterator: This is a symbol property that should be defined on an
iterable object. It returns an iterator object, which has a next() method.
Example of using an iterator with an array:
const iterable = [1, 2, 3];
const iterator = iterable[Symbol.iterator]();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
Generators in JavaScript:
Generators are a special type of function in JavaScript introduced in ES6. They
allow you to pause and resume the execution of a function, which is useful for
creating iterators, asynchronous operations, and managing complex control
flows. Generators are defined using the function* syntax and contain one or
more yield statements. When a generator function is called, it returns an
iterator called a generator object. You can use the generator object's next()
method to control the execution of the generator function.
Example of a simple generator:
function* myGenerator() { yield 1; yield 2; yield 3; }
const generator = myGenerator();
console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }
Generators are powerful for handling asynchronous operations, such as
fetching data from a server or working with streams, where you can pause
execution until data is available.
Inheritance in JavaScript:
In JavaScript, inheritance is achieved through prototype-based inheritance.
Objects inherit properties and methods from their prototype objects. You can
create constructor functions or classes and assign methods to their prototypes
to create inheritance relationships.
Example of inheritance using constructor functions and prototypes:
function Animal(name) {
this.name = name;
}
Animal.prototype.sayName = function() {
console.log("My name is " + this.name);
};
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
const myDog = new Dog("Buddy", "Golden Retriever");
myDog.sayName(); // Output: My name is Buddy
Conclusion:
Iterators in JavaScript are objects that allow you to traverse through collections
of data one element at a time. They are used with iterable data structures like
arrays and strings, and they provide a standard way to access elements using
the next() method.
Generators are special functions that allow you to pause and resume their
execution. They are defined using the function* syntax and contain yield
statements. Generators are used for creating iterators, handling asynchronous
operations, and managing complex control flows.
Inheritance in JavaScript is primarily achieved through prototype-based
inheritance. Objects inherit properties and methods from their prototype
objects. Constructor functions or classes can be used to create objects with
shared behavior. JavaScript also supports other forms of inheritance like mixin
inheritance, which allows you to mix functionality from one object into
another, and ES6 introduced a class-like syntax for inheritance, although it still
relies on prototypes under the hood
Iterator:
Generator:
Css manipulation
Arrow Function
ASSIGNMENT – 5B
THEORY:
Promises are important building blocks for asynchronous operations in JavaScript. A Promise
is a special JavaScript object.It produces a value after an asynchronous operation completes
successfully, or an error if it does not complete successfully due to time out, network error, and
so on.Successful call completions are indicated by the resolve function call, and errors are
indicated by the reject function call.They help avoid the so-called "callback hell" and make
asynchronous code easier to write and understand.
A Promise represents a value that might not be available yet, but will be resolved in the future.
It has three possible states:
• Pending: The initial state of a promise when it's created.
• Fulfilled (Resolved): The state when the promise has successfully completed its operation
and resolved to a value.
• Rejected: The state when the promise encountered an error or failed to complete its
operation.
create a promise using the promise constructor: The constructor function takes a function as an
argument. This function is called the executor function.
let promise = new Promise(function(resolve, reject) { // Make an asynchronous call and either
resolve or reject });
The executor function takes two arguments, resolve and reject.These are the callbacks provided
by the JavaScript language.For the promise to be effective, the executor function should call
either of the callback functions, resolve or reject. The new Promise() constructor returns a
promise object.As the executor function needs to handle async operations, the returned promise
object should be capable of informing when the execution has been started, completed
(resolved) or returned with error (rejected).
result – This property can have the following values:
● undefined: Initially when the state value is pending.
● value: When resolve(value) is called.
● error: When reject(error) is called
These internal properties are code-inaccessible but they are inspectable.This means that we will
be able to inspect the state and result property values using the debugger tool, but we will not
be able to access them directly using the program
Using .then() and .catch():
Once the promise is created, you can chain .then() and .catch() methods to handle the resolved
and rejected outcomes respectively.
myPromise
.then((resolvedValue) => {
// Handle successful result
})
.catch((error) => {
// Handle error
});
The .then() method takes a callback function that is executed when the promise is resolved.
The .catch() method handles errors that might occur during the promise's execution.
The .finally() handler performs cleanups like stopping a loader, closing a live connection, and
so on.The finally() method will be called irrespective of whether a promise resolves or rejects.
It passes through the result or error to the next handler which can call a .then() or .catch() again
dummyPromise.then(result => {
console.log(result); // This will be executed if the promise is resolved
}).catch(error => {
console.error(error); // This will be executed if the promise is rejected
});
// Using Promises
function fetchData() {
return new Promise((resolve, reject) => {
fetch('https://api.github.com/')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
resolve(data);
})
.catch(error => {
reject(error);
});
});
}
// Calling the fetchData function
fetchData()
.then(data => {
console.log('Fetched data:', data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Output:
Lab Assginment – 6a
Aim: WAP to implement the concept of props and state.
LAB OUTCOME:
LO5 – Construct front end application using React.
Theory:
In React, props and state are two fundamental concepts used to manage and
pass data within a component and its child components. Understanding the
difference between them is crucial for building React applications.
Props (short for Properties): Props are read-only and are used to pass data
from a parent component to a child component.
They are essentially the way you can customize and configure a component
when you use it in your application.
Props are immutable, meaning that once you pass them to a component, you
cannot change them within that component.
Props help make components reusable and maintainable by allowing you to
provide different data to the same component in different parts of your
application.
Example of using props:
// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const name = 'John';
return (
<div>
<ChildComponent name={name} />
</div>
);
}
// ChildComponent.js
import React from 'react';
function ChildComponent(props) {
return <p>Hello, {props.name}!</p>;
}
export default ChildComponent;
State:
State is used to manage and store data that can be changed or updated within
a component.
Unlike props, state is mutable and can be modified using the setState method
provided by React.
State is primarily used for managing a component's internal data and handling
user interactions or changes over time.
Components can have their own state, which is separate from the props they
receive.
When state changes, React re-renders the component to reflect the updated
data.
Example of using state:
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
incrementCount() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.incrementCount()}>Increment</button>
</div>
);
}
}
export default Counter;
Conclusion: Props are used for passing data into a component, while state is
used for managing and updating data within a component. Props are read-only,
and state is mutable. By using both props and state effectively, you can build
dynamic and interactive React applications.
functional component:
class component:
App.js
ASSIGNMENT – 6B
function App() {
return (
<div className="App">
<RegistrationForm />
</div>
);
}
3. Reusable Logic: Hooks encourage the creation of custom Hooks, which are
reusable pieces of stateful logic that can be shared across multiple components. This
promotes code reuse and cleaner code organization.
7. Improved Code Readability: Hooks can lead to cleaner and more readable code
since the logic for a particular aspect of a component (e.g., state, effects) can be
contained within a single function. This reduces the need for scattered logic across
different lifecycle methods.
Conclusion:
React Hooks are used in React applications to simplify state management and side effect
handling in functional components. They provide a more flexible and concise way to manage
component logic.
Code:
Lab Assignment – 8
Aim: WAP to implement the calculator on commandline REPL.
Lab Outcome:
LO5: To orient students to React for developing front end applications.
Theory:
Node.js Calculator Using REPL (Command-Line Input)
1. REPL (Read-Eval-Print Loop): The program utilizes a REPL environment, which stands for
Read-Eval-Print Loop. This is an interactive command-line interface where users can input
commands or expressions, and the system immediately evaluates and returns results. It's
commonly used for experimentation, testing, and quick code execution.
2. Importing Modules: The program begins by importing the 'readline' module, which is a
core Node.js module for reading input from the user in the command line. This module
provides an interface for user interaction.
3. Creating the Readline Interface: An instance of the 'readline' interface is created,
specifying that it should read input from 'stdin' (standard input) and display output in
'stdout' (standard output). The 'terminal: false' option is set to disable certain terminal-
specific features.
4. User Input and Prompts: The program uses the 'rl.question' function to prompt the user
for input in a series of steps. It starts by asking for the first number, then the second number,
and finally the desired mathematical operation (addition, subtraction, multiplication, or
division).
5. Parsing User Input: After gathering user input, the program parses the entered values into
numeric format (floats) to ensure they are suitable for mathematical operations. This step
involves using 'parseFloat' to convert the input.
6. Mathematical Operations: Depending on the user's chosen operation, the program
performs the corresponding mathematical calculation (e.g., addition, subtraction,
multiplication, or division). This is achieved using conditional statements, such as a 'switch'
statement, to determine the operation and execute the appropriate calculation.
7. Result Display: The calculated result is then displayed on the command line for the user
to see. It provides immediate feedback on the outcome of the operation.
8. Error Handling: The program includes error handling to address potential issues. For
instance, it checks for invalid inputs (non-numeric values) and handles division by zero to
prevent errors and crashes.
9. Interactive User Experience: Users interact with the program by entering input at each
prompt, and the program responds with real-time feedback, making it a user-friendly
calculator tool.
Conclusion:
In summary, the Node.js calculator program demonstrates the principles of a REPL
environment, allowing users to interactively input mathematical operations and receive
immediate results.
OUTPUT:
LAB ASSIGNMENT 9
Lab Outcome:
LO5 – To orient students to React for developing front end applications.
Theory:
React is a popular JavaScript library for building user interfaces, and it provides
various tools and patterns to efficiently manage and manipulate the Document
Object Model (DOM) elements. One of these tools is React Refs, which allow
developers to access and interact with DOM elements directly. With the introduction
of React Hooks, working with refs has become more accessible and intuitive. In this
guide, we'll explore how to create and use React refs effectively using functional
components and hooks.
It's important to check if the element exists before accessing and manipulating it
because the `current` property may initially be `null`.
c. Forward Refs:
React allows you to forward refs from a parent component to a child component.
This is particularly useful when you want to access a child's DOM element from a
parent component. To create a forward ref, use the `React.forwardRef` function:
```javascript
const ChildComponent = React.forwardRef((props, ref) => {
// JSX for child component
return <input ref={ref} /> ; });
```
In this example, the `ChildComponent` accepts a `ref` parameter and attaches it
to the `input` element. You can then use this forwarded ref in a parent
component:
```javascript
function ParentComponent() {
const childRef = useRef(null);
d. Callback Refs:
Callback refs are another way to work with refs in React. Instead of using the
`useRef` hook, you define a function that receives the DOM element as an
argument and stores it as a variable. Here's how to create and use a callback ref:
```javascript
let myRef = null;
const setMyRef = (element) => {
myRef = element; }; ``
In this example, `setMyRef` is a callback function that receives the DOM element
as an argument and assigns it to the `myRef` variable. You can then use `myRef`
to access and manipulate the DOM element. Callback refs are typically defined
inside the functional component.
React Hooks and functional refs provide a flexible and powerful way to work with
DOM elements in your React applications. Whether you're creating refs,
accessing DOM elements, forwarding refs to child components, or using callback
refs, these techniques empower you to build dynamic and interactive user
interfaces with ease.
Conclusion: In conclusion, React Hooks and functional refs offer a streamlined
approach to managing DOM elements in React applications, enhancing
accessibility and ease of use. These tools empower developers to create
dynamic and interactive user interfaces with efficiency and flexibility
LAB ASSIGNMNENT -10
AIM: Write a program in Node JS to
a. Create a file
b. Read the data from file
c. Write the data to a file
d. Rename a file
e. Append data to a file
f. Delete a file
LAB OUTCOME:
LO6 – Construct Backend Application using Node.js / Express.
THEORY:
Node.js is a runtime environment for executing JavaScript code outside of a web browser. It
is built on the V8 JavaScript engine from Google and is designed to be used for server-side
programming. Here are some key theoretical concepts and principles related to Node.js:
1. Non-Blocking and Asynchronous: One of the fundamental principles of Node.js is its non-
blocking and asynchronous nature. It uses an event-driven, single-threaded architecture that
allows it to handle many concurrent connections without blocking the execution of other
code. This makes it highly efficient for I/O-intensive operations like reading and writing to
files or making network requests.
2. Event Loop: Node.js relies on an event loop to manage asynchronous operations. The
event loop continuously checks for pending events (such as I/O operations or timers) and
executes callbacks when events are ready. This event-driven model is central to Node.js's
ability to handle concurrency.
3. Common JS Modules: Node.js uses the CommonJS module system for organizing and
managing code. Modules allow developers to break their code into reusable and
maintainable pieces. You can use the `require` function to import modules, and you can
create your own modules using `module.exports`.
4. npm (Node Package Manager):npm is the package manager for Node.js. It provides a vast
ecosystem of open-source libraries and tools that you can easily integrate into your Node.js
projects. You can use `npm` to install, manage, and share packages.
5. Single Thread with Worker Threads: While Node.js is single-threaded, it offers the
`worker_threads` module to create and manage multiple threads for CPU-intensive tasks.
This allows developers to take advantage of multi-core processors when needed.
6. Event Emitters: Many core Node.js modules and third-party libraries use event emitters to
handle and trigger events. Event emitters are a key part of creating custom event-driven
functionality in Node.js.
7. Streams: Node.js provides a built-in mechanism for working with streams of data. Streams
are useful for handling large datasets or real-time data. They can be readable (for input) or
writable (for output).
8. Error Handling: Due to its asynchronous nature, error handling in Node.js often relies on
callbacks and promises. Developers need to be mindful of handling errors correctly, and ther
are conventions for passing errors as the first argument to callbacks.
9. Blocking vs. Non-Blocking Code: Developers should be aware of the potential for blocking
code that can slow down an application. Careful design, asynchronous patterns, and utilizing
non-blocking functions can help avoid these issues.
10. Security: Node.js applications should follow best practices for security, such as input
validation, proper authentication and authorization, and keeping dependencies up to date.
These are some of the theoretical concepts and principles that form the foundation of
Node.js. Understanding these concepts is crucial for effectively developing applications with
Node.js.
CODE:
COCULISON:
This assignment provided practical knowledge for working with files and understanding the
core principles of Node.js, which are crucial for building efficient and secure server-side
applications.
LAB ASSIGNMENT 11
Aim: Create a web application that performs CRUD operations (database connectivity).
Theory:
CRUD operations
CRUD operations, which stand for Create, Read, Update, and Delete, are fundamental actions
in web applications that manipulate data. In the context of a To-Do List web app built with React
(a JavaScript library for building user interfaces) and Express.js (a Node.js framework for
building web applications), here's a short note on how these operations might be implemented:
1. Create (C):
- In your React frontend, provide a user interface where users can input and submit new
tasks.
- When a user submits a new task, send an HTTP POST request to your Express.js backend.
- In your Express.js backend, create a route and a handler to receive the POST request,
extract the task data, and add it to your database or storage.
2. Read (R):
- Display the list of tasks on the React frontend, fetching the data from your Express.js
backend.
- Create an HTTP GET request in React to retrieve the list of tasks from your Express.js API.
- In your Express.js backend, set up a route and handler to respond to the GET request by
retrieving tasks from your database and sending them as a JSON response to the frontend.
3. Update (U):
- Allow users to edit existing tasks on the React frontend by providing an edit interface.
- When a user edits a task, send an HTTP PUT request to your Express.js backend, including
the updated task data.
- In your Express.js backend, create a route and handler to receive the PUT request, update
the corresponding task in your database, and send a response indicating success.
4. Delete (D):
- Implement a mechanism in your React frontend to allow users to delete tasks, typically by
clicking a delete button next to each task.
- When a user requests to delete a task, send an HTTP DELETE request to your Express.js
backend, specifying the task to delete.
- In your Express.js backend, set up a route and handler to process the DELETE request,
remove the specified task from your database, and send a success response.
By implementing these CRUD operations, you enable users to interact with your To-Do List web
app effectively, allowing them to create, read, update, and delete tasks seamlessly. This
combination of React and Express.js provides a powerful platform for building responsive and
dynamic web applications.
MERN stack
The MERN stack, an acronym for MongoDB, Express.js, React, and Node.js, represents a
powerful and popular technology stack for building modern web applications.
Express.js, a web application framework for Node.js, functions as the backend server. It
simplifies tasks like routing, middleware integration, and handling HTTP requests and
responses, allowing for efficient backend development.
React, developed by Facebook, is the cornerstone of the frontend. This JavaScript library excels
in constructing user interfaces, leveraging a component-based architecture to create reusable
UI elements. It enables developers to build interactive, responsive user experiences.
Node.js, a runtime environment, empowers JavaScript to run on the server side. It boasts an
event-driven, non-blocking architecture, making it suitable for real-time and scalable
applications. When paired with Express.js, it creates a robust backend foundation.
The MERN stack offers several advantages, including full-stack JavaScript development,
real-time capabilities, scalability, a vibrant community, and rapid development. It's favored by
developers for its efficiency, allowing for quicker prototyping and development of web
applications that require flexibility, real-time updates, and a unified JavaScript codebase for both
frontend and backend components. In summary, the MERN stack is a versatile and widely
embraced technology stack for constructing modern web applications.
Database connectivity
2. MongoDB Drivers: Choose a MongoDB driver or library that suits your programming language
or framework. Popular options include the official MongoDB driver for JavaScript, Mongoose (an
Object Data Modeling library for Node.js), and various drivers for other languages like Python,
Java, and Ruby.
4. Connection Establishment: Use the chosen driver's API to establish a connection to the
MongoDB database. In most cases, you'll create a client or connection object that manages the
connection.
5. Database Operations: Once connected, you can perform various database operations,
including inserting, updating, querying, and deleting data. These operations are executed using
the driver's API.
7. Closing the Connection: It's good practice to close the database connection when your
application no longer needs it, typically during the application's shutdown process.
8. Security: Ensure that you follow security best practices, including properly configuring
authentication, authorization, and network access controls to protect your MongoDB database
from unauthorized access.
Connecting to MongoDB allows your application to store, retrieve, and manipulate data
efficiently. Whether you're building a web application, mobile app, or any software that relies on
data persistence, MongoDB's flexibility and scalability make it a popular choice for developers.
import mongoose from "mongoose";
import dotenv from 'dotenv';
dotenv.config();
const MONGODB_URI =
`mongodb+srv://Rudrani26:[email protected]/?retryWrite
s=true&w=majority&appName=AtlasApp`;
mongoose.connection.on('connected', () => {
console.log('Database connected Successfully');
})
mongoose.connection.on('disconnected', () => {
console.log('Database disconnected');
})
1. dotenv Configuration:
- You import the `dotenv` library and use it to load environment variables from a `.env` file.
- You retrieve the database username and password from these environment variables and
store them in `USERNAME` and `PASSWORD` constants.
2. Connection to MongoDB:
- You define a function called `Connection` that connects to a MongoDB database using
Mongoose.
- Inside this function, you construct the `MONGODB_URI` by including the username and
password retrieved from the environment variables, as well as other connection options such as
the MongoDB Atlas cluster URL and the application name.
- You use `mongoose.connect` to establish a connection to the MongoDB database using the
provided URI.
- You set up event listeners for various connection events:
- `'connected'`: This event is triggered when the connection to the database is successfully
established. It logs a success message to the console.
- `'disconnected'`: This event is triggered when the connection to the database is
disconnected. It logs a message to the console.
- `'error'`: This event is triggered when an error occurs during the connection process. It logs
an error message to the console.
3. Todo Schema:
- You import the `mongoose` library again.
- You define a Mongoose schema called `TodoSchema` for your "tasks" collection.
- The schema has three fields:
- `data`: A string field that is required.
- `done`: A boolean field with a default value of `false`.
- `createdAt`: A date field with a default value of the current date and time.
4. Todo Model:
- You create a Mongoose model called `todo` for the "tasks" collection using the
`mongoose.model` method. The first argument is the name of the collection ('tasks'), and the
second argument is the schema (`TodoSchema`).
Overall, this code sets up a connection to a MongoDB database, defines a schema for a "tasks"
collection, and creates a Mongoose model for interacting with documents in that collection. This
code appears to be part of a larger application that can perform CRUD (Create, Read, Update,
Delete) operations on tasks in the MongoDB database.
Conclusion: