0% found this document useful (0 votes)
15 views32 pages

FSD

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 32

Assignment-1

Q.1) Explain tags of HTML 5?


 Tags of HTML 5
Tag Description
<article> It defines the independent or self-contained content of a webpage.
<aside> It defines the content which provide information about the main content.
<bdi> It is used to isolate the part of text which might be formatted in another direction.
<details> It defines additional information which only visible as per user demand.
<dialog> It represents a dialog box or other interactive components.
<figcaption> It defines caption for the <figure> element.
<figure> It defines a self-contained content, and referenced as a single unit.
<footer> It represents the footer section of the webpage.
<header> It defines the introductory or navigational content of the webpage.
<main> It specifies the main content of the HTML document.
<mark> It represent the text which is highlighted or marked for reference or notation
purposes.
<meter> It represents a scalar value within a known range.
<nav> It represents the section which contains navigation links.
<progress> It defines a progress bar which shows completions progress of a task.
<rp> It defines alternative content for the browser which do not support ruby annotations.
<rt> It defines explanations and pronunciations of characters in ruby annotations.
<ruby> It defines ruby annotations (Specifically for Asian language).
<section> It defines a generic section within an HTML document.
<summary> It defines summary or caption for a <details> element which can be clicked to
change the state of <details> element.
<time> It defines data/time within an HTML document.
<wbr> It specifies a line break opportunity. (Where line break possible)

Q.2) Explain all feature of HTML5 feature with example?


 HTML5 few advance features: Semantic Elements, Audio and Video Support, Canvas
Elements, Geolocation API, Local Storage, Responsive Images, Web Workers, Drag and Drop
API, Form Enhancements, Web Sockets, Micro Data, Cross Document Messaging.
 Semantic Elements: HTML5 introduced semantic elements that provide a more meaningful way
to structure web content. These include <header>, <nav>, <main>, <article>, <section>, <aside>,
<footer>, and more. They help improve accessibility and SEO.
<header>
<h1>Website Header</h1>
</header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<main>
<article>
<h2>Article Title</h2>
<p>Article content goes here.</p>
</article>
</main>
<footer>

More Group’s Page 1


<p>&copy; 2023 Your Website</p>
</footer>

 Audio and Video Support: HTML5 introduced native support for embedding audio and video
content using the <audio> and <video> elements.
<audio controls>
<source src="audio.mp3" type="audio/mpeg"> Your browser does not support the audio element.
</audio>
<video controls width="320" height="240">
<source src="video.mp4" type="video/mp4">Your browser does not support the video element.
</video>

 Canvas: The <canvas> element allows for dynamic, scriptable rendering of 2D graphics. It's
commonly used for games, data visualization, and interactive graphics.
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);
</script>

 Geolocation: HTML5 enables websites to access the user's geographical location through the
Geolocation API.
<button onclick="getLocation()">Get Location</button>
<p id="demo"></p>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.getElementById('demo').innerHTML = 'Geolocation is not supported by
this browser.';
}
}
function showPosition(position) {
document.getElementById('demo').innerHTML = 'Latitude: ' + position.coords.latitude
+ '<br>Longitude: ' + position.coords.longitude;
}
</script>

 Drag and Drop: HTML5 enables easy implementation of drag-and-drop functionality for
elements on a web page.
<div id="dragTarget" draggable="true">Drag me!</div>
<div id="dropTarget">Drop here!</div>
<script>
var dragTarget = document.getElementById('dragTarget');
var dropTarget = document.getElementById('dropTarget');
dragTarget.addEventListener('dragstart', function (event) {
event.dataTransfer.setData('text', event.target.id);
});
dropTarget.addEventListener('dragover', function (event) {
event.preventDefault();
});

More Group’s Page 2


dropTarget.addEventListener('drop', function (event) {
event.preventDefault();
var data = event.dataTransfer.getData('text');
event.target.innerText = 'Dropped: ' + data;
});
</script>

Q.3) Describe audio & video support in HTML 5 with example?


 Audio and Video Support: One of the many HTML 5 features is the support for audio and
video. It has reduced the hassle of relying upon third-party services such as Adobe Flash player.
To embed Audio and Video into your HTML document, you may use the following two
tags, <audio> and <video> tags. These two tags are launched with the release of HTML 5 and
support a numerous range of attributes such as height, width, and more that offers developers to
leverage the customization of HTML documents.
 Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML5</title>
</head> <body>
<!-- Code to setup video -->
<video width = "300" height = "200" controls autoplay>
<source src = "./dog.mp4" type ="video/mp4" />
</video>
<!-- Code to setup audio -->
<audio controls>
<source src="dog.mp3" type="audio/mp3">
</audio> </body>
</html>

Q.4) How to importing External Style Sheets in CSS3?


 Importing External Style Sheets in CSS: At-rules are clever, powerful little huggers that
encapsulate a bunch of CSS rules and apply them to something specific. They can be used
to import other CSS files, apply CSS to a particular media, or embed funky uncommon fonts.
 @import rule allows you to import a style sheet into another style sheet.
 @import rule must be at the top of the document (but after any @charset declaration).
 @import rule also supports media queries, so you can allow the import to be media-dependent.
 Syntax: The syntax of @import rule is as follows, import /*url or list-of-media-queries*/
Value Description
url|string A url or a string representing the location of the resource to import. The url may
be absolute or relative
list-of- A comma-separated list of media queries conditioning the application of the
mediaqueries CSS rules defined in the linked URL
o The media queries can be compound statements which may specify the behavior of the document
in different media.
 The following examples implement the @import rule:
<!DOCTYPE html>
<html>
<head> <style type="text/css">
@import url(style.css);
body{
background-color: honeydew;
} </style>
</head> <body>

More Group’s Page 3


<p>This is demo paragraph one. </p>
<p class="two">This is demo paragraph two.</p>
<p>This is demo paragraph three</p>
</body>
</html>
o Import the “new-style.css" style sheet ONLY if the media is print: @import "new-style.css"
print;
o Import the “latest-style.css" style sheet ONLY if the media is screen and the viewport is
maximum 900 pixels: @import "latest-style.css" screen and (max-width: 900px);

Q.5) Short note on new Features of CSS 3?


 Some New Features of CSS 3:
1) Selectors: Selectors in CSS 3 are very interesting. They allow the designer/developer to select on
much more specific levels of the document.some selectors are:
a. matching on attributes and attribute values, including partial matches
b. structural pseudo-classes, such as the nth-child
c. a target pseudo-class to style only elements that are targetted in the URL
d. a checked pseudo-class to style any element that is checked such as radio or checkbox elements
2) Text Effects and Layout: Making changes to the hyphenation, whitespace, and justification of
text in documents.
3) First-Letter and First-Line Pseudo-Classes: CSS 3 should allow properties to affect the kerning
and alignment of drop-caps.
4) Paged Media and Generated Content: CSS 3 now supports more options in paged media, such
as running headers, footers, and page numbers. Plus there will be advanced properties for printing
generated content including properties for footnotes and cross-references.
5) Multi-Column Layout: Right now, the multi-column layout working draft provides properties to
allow designers to display their content in multiple columns with definitions like the column-gap,
column-count, and column-width.
6) Ruby: CSS will now support the ability to add small annotations on top or next to words, most
often used in Chinese and Japanese. They are generally used to give the pronunciation or meaning
of difficult ideograms.

Q.6) Describe @charset Rule in CSS 3 with syntax?


 CSS @charset Rule:
 The @charset rule specifies the character encoding used in the style sheet. The @charset rule
must be the first element in the style sheet and not be preceded by any character. If
several @charset rules are defined, only the first one is used. The @charset rule cannot be used
inside a style attribute (on an HTML element), or inside the <style> element where the character
set of the HTML page is relevant.
 Syntax:
@charset "utf-8";

Q.7) Short note on advance CSS 3 with Alpha transparency?


 Alpha transparency in CSS3 is a way to control the opacity of an element. Opacity is a measure of
how visible an element is, with a value of 1 being fully opaque and a value of 0 being fully
transparent. Alpha transparency can be used to create a variety of effects, such as:
 Fading elements in and out
 Creating ghost buttons
 Overlaying elements on top of each other
 Creating semi-transparent backgrounds
To apply alpha transparency to an element, you use the opacity property. The opacity property
accepts a value between 0 and 1, where 0 is fully transparent and 1 is fully opaque. For example,
the following CSS code will set the opacity of the div element to 50%, making it semi-
transparent:

More Group’s Page 4


div {
opacity: 0.5;
}
 Alpha transparency can also be used to create RGBA color values. RGBA color values are an
extension of RGB color values with an alpha channel, which specifies the opacity for a color. An
RGBA color value is specified with: rgba(red, green, blue, alpha)
 The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque). For
example, the following CSS code will set the background color of the div element to a semi-
transparent green color:
div {
background-color: rgba(0, 255, 0, 0.5);
}
 Alpha transparency can be used to create a variety of advanced CSS effects. For example,
you can use alpha transparency to:
 Create a ghost button that is visible when the user hovers over it, but disappears when they move
their cursor away.
 Overlay a semi-transparent image over a background image to create a fading effect.
 Create a semi-transparent background for a modal dialog to make it easier to see the underlying
content.
 Here are some examples of advanced CSS effects that can be created with alpha
transparency:
/* Ghost button */
.ghost-button {
opacity: 0.5;
transition: opacity 0.2s;
}
.ghost-button:hover {
opacity: 1;
}
/* Fading image overlay */
.image-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url('https://example.com/image.jpg');
opacity: 0.5;
}
/* Modal dialog background */
.modal-dialog {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 100;
}

Q.8) How to embed fonts in CSS 3?


 In CSS3, We can embed fonts using the @font-face rule. This rule allows you to specify custom
fonts that will be downloaded and used by the browser when rendering your web page. Here's
how you can embed fonts in CSS3:

More Group’s Page 5


1. Choose a Font: First, you need to select the font you want to embed on your website. You can
use web fonts from various sources, including Google Fonts, Adobe Fonts, or your own custom
font files (e.g., .woff or .woff2 files).
2. Download or Host the Font Files: If you're using a web font service like Google Fonts or Adobe
Fonts, they will provide you with a link to include in your HTML. If you have custom font files,
make sure they are hosted on your web server.
3. Define the @font-face Rule: In your CSS file, use the @font-face rule to define the font family
and specify the source of the font files. Here's an example:
@font-face {
font-family: 'YourFontName';
src: url('path/to/your-font.woff2') format('woff2'),
url('path/to/your-font.woff') format('woff');/* Add additional font formats here if needed */
}
o font-family: This is the name you'll use to reference the font in your CSS styles.
o src: This property specifies the source of the font files. You should provide the path to your font
files and specify the format (e.g., woff, woff2).
4. Use the Custom Font: Once you've defined the @font-face rule, you can use your custom font in
your CSS styles by specifying the font-family property:
body {
font-family: 'YourFontName', sans-serif;
}
In this example, 'YourFontName' should match the font-family name you used in the @font-face
rule. If the custom font fails to load, the browser will fall back to a generic sans-serif font.
5. Cross-Browser Compatibility: To ensure cross-browser compatibility, you may want to include
multiple font formats in your src property within the @font-face rule. Different browsers support
different font formats, so having multiple formats (e.g., woff and woff2) can improve
compatibility.
6. Font License: Make sure you have the proper licenses or permissions to use and embed the fonts
on your website, especially if you're using custom fonts.
7. Testing: After embedding the fonts, thoroughly test your website in various browsers and devices
to ensure that the fonts are loading correctly and rendering as expected.
By following these steps, you can embed custom fonts into your CSS3 styles, giving your website a
unique and distinctive typographic style.

(PPT Give you more understanding than PDF) The material for the PDF has been compiled from various sources such as books, tutorials
(offline and online), lecture notes, several resources available on Internet. The information contained in this PDF is for general information
and education purpose only. While we endeavor to keep the information up to date and correct, we make no representation of any kind
about the completeness and accuracy of the material. The information shared through this PDF material should be used for educational
purpose only.

More Group’s Page 6


Assignment-2
Q.1) Write a Short note on jQuery?
 JQuery is a fast, small, cross-platform and feature-rich JavaScript library. It is designed to
simplify the client-side scripting of HTML. It makes things like HTML document traversal and
manipulation, animation, event handling, and AJAX very simple with an easy-to-use API that
works on a lot of different type of browsers. The main purpose of jQuery is to provide an easy
way to use JavaScript on your website to make it more interactive and attractive. It is also used to
add animation.
 Following are the important features of jQuery:
o HTML manipulation, DOM manipulation, DOM element selection, CSS manipulation, Effects
and Animations, Utilities, AJAX, HTML event methods, JSON Parsing, Extensibility through
plug-ins.

Q.2) Describe about jQuery DOM Manipulation?


 JQuery DOM Manipulation: jQuery provides methods such as attr(), html(), text() and val()
which act as getters and setters to manipulate the content from HTML documents. Document
Object Model (DOM) - is a W3C (World Wide Web Consortium) standard that allows us to
create, change, or remove elements from the HTML or XML documents.
 Here are some basic operations which you can perform on DOM elements with the help of
jQuery standard library methods:
o Extract the content of an element
o Change the content of an element
o Adding a child element under an existing element
o Adding a parent element above an existing element
o Adding an element before or after an existing element
o Replace an existing element with another element
o Delete an existing element
o Wrapping content with-in an element

Q.3) How to Call a jQuery Library Functions?


 If you want an event to work on your page, you should call it inside the $(document).ready()
function. Everything inside it will load as soon as the DOM is loaded and before the page contents
are loaded. To do this, we register a ready event for the document as follows:
$(document).ready(function() {
// do stuff when DOM is ready
});
 To call upon any jQuery library function, use HTML script tags as shown below:
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("div").click(function() {alert("Hello, world!");});
});
</script> </head>
<body>
<div>Click on this to see a dialogue box.</div>
</body> </html>

Q.4) Explain jQuery DOM Manipulation methods?


 JQuery DOM Manipulation: jQuery provides various methods to add, edit or delete DOM
element(s) in the HTML page. The following table lists some important methods to add/remove
new DOM elements.

More Group’s Page 1


Method Description
append() Inserts content to the end of element(s) which is specified by a selector.
before() Inserts content (new or existing DOM elements) before an element(s) which is
specified by a selector.
after() Inserts content (new or existing DOM elements) after an element(s) which is
specified by a selector.
prepend() Insert content at the beginning of an element(s) specified by a selector.
remove() Removes element(s) from DOM which is specified by selector.
replaceAll() Replace target element(s) with specified element.
wrap() Wrap an HTML structure around each element which is specified by selector.

Q.5) Explain CSS Manipulation using jQuery library methods?


 CSS Manipulation using jQuery: CSS manipulation using jQuery library methods allows you to
dynamically modify the styles of HTML elements on a web page. jQuery provides several
methods for working with CSS properties, including css(), addClass(), hasClass(), removeClass(),
and toggleClass(). These methods make it easy to change the appearance and behavior of
elements in response to user interactions or other events.
 css(): The css() method allows you to get or set CSS properties for one or more elements. You
can use it to both retrieve and change the values of CSS properties. Here's an example of how to
use it:
// Get the value of a CSS property
var fontSize = $('#myElement').css('font-size');
// Set the value of a CSS property
$('#myElement').css('color', 'red');
 addClass(): The addClass() method adds one or more CSS classes to selected elements. This can
be used to apply predefined styles to elements or add new styles dynamically. For example:
$('#myElement').addClass('highlighted');
 hasClass(): The hasClass() method checks if a selected element has a specific CSS class. It
returns true if the class exists on the element and false otherwise. This is useful for conditionally
applying styles based on whether an element has a certain class:
if ($('#myElement').hasClass('highlighted')) {
// Do something if the element has the 'highlighted' class
}
 removeClass(): The removeClass() method removes one or more CSS classes from selected
elements. This is helpful for removing styles or toggling the appearance of elements. For
example:
$('#myElement').removeClass('highlighted');
 toggleClass(): The toggleClass() method toggles the presence of a CSS class on selected
elements. If the class is present, it is removed; if it's not present, it's added. This is often used for
creating interactive elements like buttons that change appearance when clicked:
// Toggle a CSS class on an element$('#myButton').click(function() {
$('#myElement').toggleClass('active');
});
o These jQuery CSS manipulation methods are powerful tools for creating dynamic and interactive
web pages. They allow you to easily change styles, apply animations, and respond to user actions
without the need for complex JavaScript and CSS code.

Q.6) Short note on jQuery dimensions with diagram?


 JQuery dimensions: jQuery has several important methods for working with dimensions:
width(), height(), innerWidth(), innerHeight(), outerWidth(), outerHeight().
 JQuery width() and height() Methods: The width() method sets or returns the width of an
element (excludes padding, border and margin). The height() method sets or returns the height of
an element (excludes padding, border and margin). The following example returns the width and

More Group’s Page 2


height of a specified <div> element:
$("button").click(function(){
var txt = "";
txt += "Width: " + $("#div1").width() + "</br>";
txt += "Height: " + $("#div1").height();
$("#div1").html(txt);
});
 JQuery innerWidth() and innerHeight()
Methods: The innerWidth() method returns the
width of an element (includes padding).
The innerHeight() method returns the height of an
element (includes padding). The following
example returns the inner-width/height of a
specified <div> element:
$("button").click(function(){
var txt = "";
txt += "Inner width: " + $("#div1").innerWidth() + "</br>";
txt += "Inner height: " + $("#div1").innerHeight();
$("#div1").html(txt);
});
 JQuery outerWidth() and outerHeight() Methods: The outerWidth() method returns the width
of an element (includes padding and border). The outerHeight() method returns the height of an
element (includes padding and border). The following example returns the outer-width/height of a
specified <div> element:
$("button").click(function() {
var txt = "";
txt += "Outer width: " + $("#div1").outerWidth() + "</br>";
txt += "Outer height: " + $("#div1").outerHeight();
$("#div1").html(txt);
});
 JQuery More width() and height(): The following example returns the width and height of the
document (the HTML document) and window (the browser viewport):
$("button").click(function(){
var txt = "";
txt += "Document width/height: " + $(document).width();
txt += "x" + $(document).height() + "\n";
txt += "Window width/height: " + $(window).width();
txt += "x" + $(window).height();
alert(txt);
});

Q.7) What is Jquery Traversing? Explain why it is necessary?


 JQuery Traversing: JQuery is a very powerful tool that provides a variety of DOM traversal
methods to assist us in selecting elements in an HTML or XML document in both a random and
sequential manner.
o The DOM organizes elements into a tree-like data structure that can be traversed to navigate and
locate content within an HTML or XML document.
o The DOM tree can be thought of as a collection of nodes connected by parent-child and sibling-
sibling relationships, with the root starting from the top parent, which is an HTML element in an
HTML document.
 DOM traversing using jQuery: It is used to find (or select) HTML elements based on their
relationship to other elements. Begin with one option and work your way through it until you
reach the desired elements.
o An HTML page is depicted as a tree in the image below (DOM tree). You can easily move

More Group’s Page 3


up(ancestors), down(descendants), and sideways(siblings) in the tree using jQuery traversing,
starting from the selected (current) element. This is known as traversing - or moving through
the DOM tree.
o jQuery provides a number of methods for traversing the DOM. Tree traversal is the most common
type of traversal method. An ancestor is a parent, grandparent, great-grandparent, and so on in
logical relationships.
o jQuery provides useful methods such as parent(), parents(), and parentsUntil() that can be used to
traverse the DOM tree on single or multiple levels to quickly get the parent or other ancestors of
an element in the hierarchy.
o The majority of DOM Traversal Methods do not modify the jQuery DOM object and are used to
filter out elements from a document based on specified conditions.
 jQuery provides methods for traversing in three directions:
 Traversing Upwards - This path leads to the ancestors (Parent, Grandparent, Great-grandparent).
 Traversing Downwards- entails traversing the descendants in this direction (Child, Grandchild,
Great-grandchild).
 Sideways - Traveling in this direction means passing through the ancestors and siblings (For
example, brother and sisters are at the same level).

Q.8) Explain jQuery methods for traversing in Upwards?


 Traversing Up the DOM Tree: Three useful jQuery methods for traversing up the DOM tree
are: parent(), parents(), parentsUntil().
 jQuery parent() Method: The parent() method returns the direct parent element of the selected
element. This method only traverse a single level up the DOM tree. The following example
returns the direct parent element of each <span> elements:
$(document).ready(function(){
$("span").parent();
});
 jQuery parents() Method: The parents() method returns all ancestor elements of the selected
element, all the way up to the document's root element (<html>). The following example returns
all ancestors of all <span> elements:
$(document).ready(function(){
$("span").parents();
});
 jQuery parentsUntil() Method: The parentsUntil() method returns all ancestor elements
between two given arguments. The following example returns all ancestor elements between
a <span> and a <div> element:
$(document).ready(function(){
$("span").parentsUntil("div");
});

Q.9) Explain jQuery methods for traversing in Downwards?


 Traversing Down the DOM Tree: Two useful jQuery methods for traversing down the DOM
tree are: children() & find()
 jQuery children() Method: The children() method returns all direct children of the selected
element. This method only traverses a single level down the DOM tree. The following example
returns all elements that are direct children of each <div> elements:
Example1:
$(document).ready(function(){
$("div").children();
});
Example2:
$(document).ready(function(){
$("div").children("p.first");
});

More Group’s Page 4


 jQuery find() Method: The find() method returns descendant elements of the selected element,
all the way down to the last descendant. The following example returns all <span> elements that
are descendants of <div>:
Example1:
$(document).ready(function(){
$("div").find("span");
});
Example2:
$(document).ready(function(){
$("div").find("*");
});

Q.10) Explain jQuery methods for traversing in sideways?


 JQuery methods for traversing in sideways: Traveling in this direction means passing through
the ancestors and siblings (For example, brother and sisters are at the same level).With jQuery
you can traverse sideways in the DOM tree to find siblings of an element. Siblings share the same
parent. Traversing Sideways in The DOM Tree. There are many useful jQuery methods for
traversing sideways in the DOM tree: siblings(), next(), nextAll(), nextUntil(), prev(), prevAll(),
prevUntil().
 jQuery siblings() Method: The siblings() method returns all sibling elements of the selected
element. The following example returns all sibling elements of <h2>:
$(document).ready(function(){
$("h2").siblings();
})
 jQuery next() Method: The next() method returns the next sibling element of the selected
element. The following example returns the next sibling of <h2>:
$(document).ready(function(){
$("h2").next();});
 jQuery nextAll() Method: The nextAll() method returns all next sibling elements of the selected
element. The following example returns all next sibling elements of <h2>:
$(document).ready(function(){
$("h2").nextAll();
});
 jQuery nextUntil() Method: The nextUntil() method returns all next sibling elements between
two given arguments.The following example returns all sibling elements between a <h2> and
a <h6> element:
$(document).ready(function(){
$("h2").nextUntil("h6");
});
 jQuery prev(), prevAll() & prevUntil() Methods:The prev(), prevAll() and prevUntil() methods
work just like the methods above but with reverse functionality: they return previous sibling
elements (traverse backwards along sibling elements in the DOM tree, instead of forward).

(PPT Give you more understanding than PDF) The material for the PDF has been compiled from various sources such as books, tutorials
(offline and online), lecture notes, several resources available on Internet. The information contained in this PDF is for general information
and education purpose only. While we endeavor to keep the information up to date and correct, we make no representation of any kind
about the completeness and accuracy of the material. The information shared through this PDF material should be used for educational
purpose only.

More Group’s Page 5


Assignment-3

Q.1) What is Angular JS with ng directives?


 AngularJS extends HTML with ng-directives: The ng-app directive defines an AngularJS
application. The ng-model directive binds the value of HTML controls (input, select, textarea) to
application data. The ng-bind directive binds application data to the HTML view.
Example: <!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>

Q.2) Write & Explain Setup Angular JS Development Environment?


 We need the following tools to setup a development environment for AngularJS: AngularJS,
Library, Editor/IDE, Browser, Web server.
 AngularJS Library: To download AngularJS library, go to angularjs.org -> click download
button, which will open the following popup.
 Editor: AngularJS is eventually HTML and JavaScript code. So you can install any good
editor/IDE as per your choice. The following editors are recommended: Sublime Text, Aptana
Studio 3, Ultra Edit, Eclipse, Visual Studio.
 Online Editor: You can also use the following online editors for learning purpose. plnkr.co,
jsbin.com. We are using our own online code editor for all the AngularJS examples in these
tutorials.
 Web server: Use any web server such as IIS, apache etc., locally for development purpose.
 Browser: You can install any browser of your choice as AngularJS supports cross-browser
compatibility. However, it is recommended to use Google Chrome while developing an
application.

Q.3) Explain with diagram MVC Architecture?


 MVC Architecture: Model View Controller or MVC as it is popularly called, is a software
design pattern for developing web applications. MVC is popular because it isolates the application
logic from the user interface layer and supports separation of concerns. The controller receives all
requests for the application and then works with the model to prepare any data needed by the
view. The view then uses the data prepared by the controller to generate a final presentable
response.
 The MVC pattern is made up of the following three parts:
o Model: It is responsible for managing application data. It
responds to the requests from view and to the instructions from
controller to update itself.
o View: It is responsible for displaying all data or only a portion of
data to the users. It also specifies the data in a particular format
triggered by the controller's decision to present the data. They are
script-based template systems such as JSP, ASP, PHP and very
easy to integrate with AJAX technology.
o Controller: It is responsible to control the relation between
models and views. It responds to user input and performs
interactions on the data model objects. The controller receives
input, validates it, and then performs business operations that
modify the state of the data model.

More Group’s Page 1


Q.4) Short note on Directive & Why it uses in Angular-JS?
 Angular-JS Directive: Directives are markers on the DOM element which tell AngularJS to
attach a specified behavior to that DOM element or even transform the DOM element with its
children. Simple Angular-JS allows extending HTML with new attributes called Directives.
Angular-JS has a set of built-in directives which offers functionality to the applications. It also
defines its own directives. A directive can be defined using some functions which are: Element
name, Attribute, Class, and Comment.
 Why use Directive in Angular-JS:
o It gives support to creating custom directives for different types of elements.
o A directive is activated when the same element or matching element is there in front.
o It is used to give more power to HTML by helping them with the new syntax.
o Directive classes, like component classes, can implement life-cycle hooks to influence their
configuration and behavior.

Q.5) Which are Directive Components in Angular-JS?


 The Angular-JS directives extend the attribute with the prefix ng-. Some directive
components are discussed below:
1. Ng-app: The ng-app directive is used to define the root element of an Angular-JS application.
This directive automatically initializes the Angular-JS application on page load. Example: This
example illustrates the implementation of the ng-app directive in Angular-JS.
<!DOCTYPE html>
<html>
<head> <title> AngularJS ng-app Directive </title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script>
</head>
<body style="text-align:center">
<h1 style="color:green">More Group’s</h1>
<h3 style="color:green">ng-app directive</h3>
<div ng-app="" ng-init="name=' More Group’s '">
<p>{{ name }} is the portal for More Group’s.</p> </div>
</body> </html>

2. Ng-controller: The ng-controller Directive in AngularJS is used to add the controller to the
application. It can be used to add methods, functions, and variables that can be called on some
event like a click, etc to perform a certain action. Example: This example illustrates the
implementation of the ng-controller directive in AngularJS.
<!DOCTYPE html>
<html>
<head> <title>AngularJS ng-controller Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="MyController">
<h1>{{ greeting }}</h1> <button ng-click="changeGreeting()">Change Greeting</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
$scope.greeting = 'Hello, World!';
$scope.changeGreeting = function() {
$scope.greeting = 'New Greeting!';
}; });
</script>
</body></html>

More Group’s Page 2


3. Ng-bind: The ng-bind directive is used to bind/replace the text content of a particular element
with the value that is entered in the given expression. The value of specified HTML content
updates whenever the value of the expression changes in the ng-bind directive. Example: This
example illustrates the implementation of the ng-bind directive in AngularJS.
<!DOCTYPE html>
<html>
<head> <title>AngularJS ng-bind Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="MyController">
<h1 ng-bind="greeting"></h1> <button ng-click="changeGreeting()">Change
Greeting</button> </div>
<script>
var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
$scope.greeting = 'Hello, World!';
$scope.changeGreeting = function() {
$scope.greeting = 'New Greeting!';
};
});
</script>
</body>
</html>

Q.6) Describe AngularJS Expressions with example?


 AngularJS Expressions: AngularJS binds data to HTML using Expressions. AngularJS
expressions can be written inside double braces: {{ expression }}. AngularJS expressions can also
be written inside a directive: ng-bind="expression". AngularJS will resolve the expression, and
return the result exactly where the expression is written. AngularJS expressions are much
like JavaScript expressions: They can contain literals, operators, and variables.
 Example: {{ 5 + 5 }} or {{ firstName + " " + lastName }}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body> <div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>

Q.7) Explain AngularJS Controllers with example?


 AngularJS controllers are used to control the flow of data of AngularJS application. A controller
is defined using ng-controller directive. A controller is a JavaScript object containing
attributes/properties and functions. Each controller accepts $scope as a parameter which refers to
the application/module that controller is to control. The ng-controller directive defines the
application controller. A controller is a JavaScript Object, created by a standard JavaScript object
constructor.
 Use controllers to: Set up the initial state of the $scope object, Add behavior to
the $scope object.
 Do not use controllers to:
 Manipulate DOM: Controllers should contain only business logic. Putting any presentation logic
into Controllers significantly affects its testability. AngularJS has databinding for most cases

More Group’s Page 3


and directives to encapsulate manual DOM manipulation.
 Format input: Use AngularJS form controls instead.
 Filter output: Use AngularJS filters instead.
 Share code or state across controllers: Use AngularJS services instead. Manage the life-cycle of
other components (for example, to create service instances).
 Angular-JS Controller Example: The example above demonstrated a controller object with two
properties: lastName and firstName. A controller can also have methods (variables as functions):
<!DOCTYPE html>
<html>
<head> <title>AngularJS User Information Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "Aryan";
$scope.lastName = "Khanna"; });
</script>
</body></html>

Q.8) Life Cycle of Angular-JS Scope with diagram?


 Life Cycle of Angular-JS Scope: In the flow of javascript code, whenever an event is received
by browser then it executes a javascript callback corresponding to it. --And after the completion
of callback, DOM objects are re-rendered by a browser. If any javascript code is executed outside
the context of angularJS by browser then angularJS remain unaware with the changes in the
model. To detect the model change in angularJS $apply API is used.
 Importance of Scope lifecycle: This lifecycle is used right from the creation to the destruction
phase and thus makes it easier for the developer to create applications. Since it uses functions like
$apply(), and $digest() it protects the application from any security mishap. Model mutation acts
as a boon for developers in Angular as it monitors the code as well as updates and reflects the
changes made. Whenever any child scope is not required, it is destroyed which lowers the load on
the server as well as the chunk of memory allocated to the scope is made free.
 Life Cycle of AngularJS Scope:
1. Creation: During bootstrap of an application using $injector, root
scope is created. And during the linking of a template, many of the
directives creates new child scope.
2. Watcher Registration: Model values can propagate to DOM using
a $watch
3. Model Mutation: To observe mutation in a proper way, an API
known as $apply is used.
4. Mutation Observation: After $apply, a $digest is performed on the
root scope in angular JS.
5. Scope Destruction: If child scope is no longer in use, then it should
be destroyed. Child scope creator is responsible to destroy the child
scope if no longer in use. Using API $scope.$destroy() child scope
creator can do so. Destroying an unused child scope will release
memory that is being used by it and stop model propagation too.

More Group’s Page 4


Q.9) Explain in detail AngularJS Data Binding with example?
 AngularJS Data Binding: Data binding in AngularJS is the synchronization between the model
and the view. AngularJS implements data-binding that treats the model as the single-source-of-
truth in your application & for all the time, the view is a projection of the model.
1. One-way Binding: This type of binding is unidirectional, i.e. this binds the data flow from either
component to view(DOM) or from the view(DOM) to the component. There are various
techniques through which the data flow can be bind from component to view or vice-versa. If
the data flow from component to view(DOM), then this task can be accomplished with the help
of String Interpolation & Property Binding.
 Interpolation: Angular interpolation is used to display a component property in the respective
view template with double curly braces syntax. Interpolation is used to transfer properties
mentioned in the component class to be reflected in its template.
 Property Binding: Similar to Java, variables defined in the parent class can be inherited by the
child class which is templates in this case. So if we have to store Boolean or other data types then
use Property Binding.
Syntax: class="{{variable_name}}"
Example:
<h3>Binding Types</h3>
<p>Interpolation</p> <br>
<h5>
Addition of 3 and 5 with
Interpolation is {{3+5}}
</h5>
<h5>
Addition of 3 and 5 without
Interpolation is 3+5
</h5>
<h2>{{val}}</h2>
2. Event Binding: An event is created whenever either a key is pressed or on a mouse clicked. It is
used to handle the events raised by the user actions like button click, mouse movement,
keystrokes, etc. When the DOM event happens at an element(e.g. click, keydown, keyup), it calls
the specified method in the particular component.Using Event Binding, we can bind data from
DOM to the component and hence can use that data for further purposes.
<h3>Binding Types</h3>
<p>Event Binding</p>
<button class="btn btn-block" (click)="Clickme($event)"> Click Here </button>
3. Two way Binding: In this type of binding, the immediate changes to the view & component, will
be reflected automatically, i.e. when the changes made to the component or model then
the view will render the changes simultaneously. Similarly, when the data is altered or modified
in the view then the model or component will be updated accordingly.
div style="text-align: center">
<h1 style="color: green">
GeeksforGeeks
</h1>
<h3>Two-way Data Binding</h3>
<input type="text"
placeholder="Enter text"
[(ngModel)]="val" />
<br />
{{ val }}
</div>

More Group’s Page 5


Q.10) Describe AngularJS component?
 A component is a directive that uses a more straightforward configuration that fits a component-
based architecture, which Angular 2 is all about. Think of an element as a widget: A piece of
HTML code that you can reuse in various places in your web application.
 Components: app.component.css, app.component.html, app.component.spec.ts,
app.component.ts, app.module.ts. These are the component files that get created by default when
you create an application in Angular.
 Types of Components in Angular: Parent, Child. The Parent Component is the one that is
predefined and imported when you create the App. However, the Child component is the one that
you can design according to your needs and demand.
 Metadata of Angular Component:
 There is three-component configuration
import {Component} from ‘@angular/core’;
@Component({
Selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
providers: [”]
})
export class AppComponent {
title=‘ExternLabs’;
}
 Angular components overview: Components are the main building blocks for Angular
applications. Each component consists of:
 An HTML template that declares what renders on the page
 A TypeScript class that defines behavior
 A CSS selector that defines how the component is used in a template Optionally, CSS styles
applied to the template.
 In AngularJS, a Component is a special kind of directive that uses a simpler configuration which
is suitable for a component-based application structure. This makes it easier to write an app in a
way that's similar to using Web Components or using the new Angular's style of application
architecture.

Q.11) Short note on Angular js services?


 The Services is a function or an object that avails or limit to the application in AngularJS ie., it is
used to create variables/data that can be shared and can be used outside the component in which it
is defined. Service facilitates built-in service or can make our own service. The Service can only
be used inside the controller if it is defined as a dependency.
 Why to use the AngularJS Service: AngularJS supervise the application constantly. In order to
handle the events or any changes in a proper manner, then the Service that is provided by the
AngularJS will prefer to use, instead of Javascript Objects.
 There are some commonly used built-in services, are described below:
o $http Service: It makes the request to the server, in order to handle the response by the
application.
o $timeout Service: This service is AngularJS’ version of the window.setTimeout function.
o $interval Service: This service is AngularJS’ version of the window.setInterval function.
 Create the AngularJS Service:
o STEP 1: Creating a service will follow the below command: ng g s service-name. s is a short
form for service. This creates two files service-name.service.spec.ts which is not supposed to be
changed and service-name.service.ts.
o STEP 2: After the service is created, we have to include it in the providers of app.module.ts,
providers: [Service-nameService], Here, the first letter of the service-name should be capitalized
followed by Service written without any space.
o STEP 3: So we have to now make changes in service-name.service.ts to create a JSON variable

More Group’s Page 6


that is supposed to be made available to various components, Sailors = [22, ‘Dustin’, 7]; The
sailors variable here is an array.
o STEP 4: In app.component.ts make the following changes:
o import the service among the rest of the required imports. Example: import { Service-
nameService } from './service-name.service'; just like the way we did it in providers.
o STEP 5: In app.component.html we will print the data stored in newData: {{newData}}
o Note: As we have added ngFor in app.component.html we will have to import FormsModule
in app.module.ts

Q.12) Explain in brief AngularJS Dependency Injection with example?


 AngularJS Dependency Injection: AngularJS comes with a built-in dependency injection
mechanism. It facilitates you to divide your application into multiple different types of
components which can be injected into each other as dependencies. Dependency Injection is a
software design pattern that specifies how components get holds of their dependencies. In this
pattern, components are given their dependencies instead of coding them within the component.
Modularizing your application makes it easier to reuse, configure and test the components in your
application. It provides following core components which can be injected into each other as
dependencies: Value, Factory, Service, Provider, Constant.
 Value: Value is a simple JavaScript object, which is required to pass values to the controller
during config phase (config phase is when AngularJS bootstraps itself).
//define a module
var mainApp = angular.module("mainApp", []);
//create a value object as "defaultInput" and pass it a data.
mainApp.value("defaultInput", 5);
//inject the value in the controller using its name "defaultInput"
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
} });
 Factory: Factory is a function which is used to return value. It creates a value on demand
whenever a service or a controller requires it. It generally uses a factory function to calculate and
return the value..
//define a module
var mainApp = angular.module("mainApp", []);
//create a factory "MathService" which provides a method multiply to return multiplication of
two numbers
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
//inject the factory "MathService" in a service to utilize the multiply method of factory.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
} });
 Service: Service is a singleton JavaScript object containing a set of functions to perform certain
tasks. Service is defined using service() function and it is then injected into the controllers.
//define a module
var mainApp = angular.module("mainApp", []);

More Group’s Page 7


//create a service which defines a method square to return square of a number.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a); }
});
//inject the service "CalcService" into the controller
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
} });
 Provider: Provider is used by AngularJS internally to create services, factory, etc. during the
config phase. The following script can be used to create MathService that we created earlier. --
Provider is a special factory method with get() method which is used to return the
value/service/factory.
//define a module
var mainApp = angular.module("mainApp", []);
//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
 Constant: Constants are used to pass values at the config phase considering the fact that value
cannot be used during the config phase.
mainApp.constant("configParam", "constant value")

(PPT Give you more understanding than PDF) The material for the PDF has been compiled from various sources such as books, tutorials
(offline and online), lecture notes, several resources available on Internet. The information contained in this PDF is for general information
and education purpose only. While we endeavor to keep the information up to date and correct, we make no representation of any kind
about the completeness and accuracy of the material. The information shared through this PDF material should be used for educational
purpose only.

More Group’s Page 8


Assignment-4

Q.1) Write short note on arrow Functions with syntax?


 JavaScript Arrow Function: Arrow function {() =>} is concise way of writing Javasript
functions in shorter way. Arrow functions were introduced in the ES6 version. They make our
code more structured and readable. Arrow function is one of the features introduced in the ES6
(ES6 stands for ECMA Script6. ECMA Script was created to standardize JavaScript, and ES6 is
the 6th version of ECMA Script, it was published in 2015, and is also known as ECMA Script
2015.) version of JavaScript. It allows you to create functions in a cleaner way compared to
regular functions. .
Example: // function expression
let x = function(x, y) { return x * }
 can be written as
// using arrow functions
let x = (x, y) => x * y;
 Arrow Function Syntax: The syntax of the arrow function is:
myFunction = (arg1, arg2, ...argN) => { statement(s) }
Here, myFunction is the name of the function, arg1, arg2, ...argN are the function arguments,
statement(s) is the function body.
If the body has single statement or expression, you can write arrow function as:
let myFunction = (arg1, arg2, ...argN) => expression

Q.2) What is Template Strings OR Template literals with syntax?


 Template Strings OR Template literals are literals delimited with backtick (`) characters,
allowing for multi-line strings, string interpolation with embedded expressions, And special
constructs called tagged templates. Template literals are sometimes informally called template
strings, because they are used most commonly for string interpolation (to create strings by doing
substitution of placeholders). However, a tagged template literal may not result in a string; it can
be used with a custom tag function to perform whatever operations you want on the different parts
of the template literal. Synonyms: Template Literals, Template Strings, String Templates, Back-
Tics Syntax.
 Syntax: Template Literals use back-ticks (``) rather than the quotes ("") to define a string:
let text = `Hello World!`;
OR
let text = `He's often called "Johnny"`;
OR Multi-line
let text =
`The quick
brown fox
jumps over
the lazy dog`;

Q.3) Explain with syntax rest parameter & Spread Operator?


 The rest parameter: The rest parameter is an improved way to handle function parameters,
allowing us to more easily handle various inputs as parameters in a function. The rest parameter
syntax allows us to represent an indefinite number of arguments as an array. With the help of a
rest parameter, a function can be called with any number of arguments, no matter how it was
defined. Rest parameter is added in ES2015 or ES6 which improved the ability to handle
parameter.
Syntax:
/... is the rest parameter (triple dots)
function functionname(...parameters)
{
statement;

More Group’s Page 1


}
 Spread Operator: The JavaScript spread operator (...) allows us to quickly copy all or part of an
existing array or object into another array or object. The spread operator ... is used to expand or
spread an iterable or an array.
Example:
const arrValue = ['My', 'name', 'is', 'Jack']; console.log(arrValue); // ["My", "name", "is", "Jack"]
console.log(...arrValue); // My name is Jack
Output:
[ 'My', 'name', 'is', 'Jack' ]
My name is Jack

Q.4) What is Java Scripts Object Literals? Explain example & syntax?
 Object literals are one of the most commonly used data structures in JavaScript. They are used to
store collections of data, and can be used to represent complex data structures such as objects,
arrays, functions, and even regular expressions. Object literals are also used to store information
about a particular instance of an object, such as its state or behavior. Object literals are written in
the form of key-value pairs, where each key is a string and each value can be any valid JavaScript
data type.
 For example, the following object literal stores information about a person:
script.js
const person = {
name: 'John Doe', age: 30, address: '123 Main Street'
};
 Example:
const person = {  In the example above, this refers to
firstName: "John", the person object. In this first Name means
lastName : "Doe", the first Name property of this. In this First
id : 5566, Name means the firstName property
fullName : function() { of person.
return this.firstName + " " + this.lastName;
}
};.

Q.5) Short note on JavaScript Object Destructuring & example?


 Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and
maps and set them into new, distinct variables. The destructuring assignment syntax is a
JavaScript expression that makes it possible to unpack values from arrays, or properties from
objects, into distinct variables. Destructuring allows us to extract multiple properties, or items,
from an array at a time. JavaScript Object Destructuring is the syntax for extracting values from
an object property and assigning them to a variable. The destructuring is also possible for
JavaScript Arrays. By default, the object key name becomes the variable that holds the respective
value. Here is the old way of assigning array items to a variable:
const vehicles = ['mustang', 'f-150', 'expedition'];
// old way
const car = vehicles[0];
const truck = vehicles[1];
const suv = vehicles[2];
 Example:ith destructuring:
const vehicles = ['mustang', 'f-150', 'expedition'];
const [car, truck, suv] = vehicles;
 When destructuring arrays, the order that variables are declared is important. If we only want the
car and suv we can simply leave out the truck but keep the comma:
const vehicles = ['mustang', 'f-150', 'expedition'];
const [car,, suv] = vehicles;

More Group’s Page 2


Q.6) Explain JavaScript inheritance with syntax?
 Inheritance refers to the act of inheriting something. It could be a child inheriting the property of
their parents or a new species inheriting some property of the older species during evolution. Even
in programming, the concept of inheritance exists. Inheritance in javascript aids a new class to
have all the functionality of another class while having its own functionality as well. The
inheritance in javascript primarily involves two segments:
 Child class: The class which inherits the properties of another class is known as the child class.
 Parent class: The class whose property is being inherited is known as the parent class. This can
be done using the extends and super keywords. We use the extends keyword to implement the
inheritance in ES6. Let‟s see the ES6 version of inheritance:
class Shape {
constructor( color ) {
this.color = color; }
getColor() {
return this.color; }
}
class Rectangle extends Shape {
constructor( color, width, height ) {
super( color );
this.width = width;
this.height = height; }
getArea() {
return this.width * this.height;
} }
let rectangle = new Rectangle( 'red', 5, 8 );
console.log( "Area:\t\t" + rectangle.getArea()
);
console.log( "Color:\t\t" +
rectangle.getColor() );
console.log( "toString:\t" +
rectangle.toString() );

Q.7) Explain JavaScript split & substr with syntax & example?
 The split() method splits (divides) a string into two or more substrings depending on a splitter
(or divider). The splitter can be a single character, another string, or a regular expression. After
splitting the string into multiple substrings, the split() method puts them in an array and returns it.
1. String split() method: The String.prototype.split() divides a string into an array of substrings:
split([separator, [,limit]]);
a. Separator : The separator determines where each split should occur in the original string. The
separator can be a string. Or it can be a regular expression. If you omit the separator or
the split() cannot find the separator in the string, the split() returns the entire string.
b. Limit : The limit is zero or positive integer that specifies the number of substrings.
The split() method will stop when the number of substrings equals to the limit. If the limit is zero,
the split() returns an empty array. If the limit is 1, the split() returns an array that contains the
string.
 Let’s take some examples of using the split() method.
I. Splitting the strings into words example:
let str = 'JavaScript String split()';
let substrings = str.split(' ');
console.log(substrings);Code language: JavaScript (javascript)
Output:
["JavaScript", "String", "split()"]Code language:
JavaScript (javascript)

More Group’s Page 3


Note: space („ „) has been removed in the substrings.

II. Returning a limited number of substrings example: The following example uses
the split() method to divide a string into substrings using the space separator. It also uses the
second parameter to limit the number of substrings to two:
let str = 'JavaScript String split()';
let substrings = str.split(' ',2);
console.log(substrings);
Code language: JavaScript (javascript)
Output:
["JavaScript", "String"]
Summary: Use the JavaScript String split() to divide a string into an array of substrings by a
separator. Use the second parameter (limit) to return a limited number of splits.
2. JavaScript substr(): The substr() method extracts a part of a string. The substr() method begins
at a specified position, and returns a specified number of characters. The substr() method does
not change the original string. To extract characters from the end of the string, use a negative start
position.
I. Extracting a substring from the beginning of the string example: The following example
uses the substring method to extract a substring starting from the beginning of the string:
let str = 'JavaScript Substring';
let substring = str.substring(0,10);
console.log(substring);
Output:
JavaScript

II. Extracting a substring to the end of the string example: The following example uses the
substring() to extract a substring from the index 11 to the end of the string:
let str = 'JavaScript Substring';
let substring = str.substring(11);
console.log(substring);
Output:
Substring

III. Extracting domain from the email example: The following example uses
the substring() with the indexOf() to extract the domain from the email:
let email = 'john.doe@gmail.com';
let domain = email.substring(email.indexOf('@') + 1); console.log(domain);
How it works: First, the indexOf() returns the position of the @ character, Then the substring
returns the domain that starts from the index of @ plus 1 to the end of the string.
Summary :The JavaScript substring() returns the substring from a string between the start and
end indexes.

Q.8) What is Try...Catch And Throw block in JS?


 The try statement defines a code block to run (to try): The catch statement defines a code
block to handle any error. The finally statement defines a code block to run regardless of the
result. The throw statement defines a custom error.
 try{} statement: Here, the code which needs possible error testing is kept within the try block. In
case any error occur, it passes to the catch{} block for taking suitable actions and handle the error.
Otherwise, it executes the code written within.
 catch{} statement: This block handles the error of the code by executing the set of statements
written within the block. This block contains either the user-defined exception handler or the
built-in handler. This block executes only when any error-prone code needs to be handled in the
try block. Otherwise, the catch block is skipped.
 Throw Statement: Throw statements are used for throwing user-defined errors. User can define

More Group’s Page 4


and throw their own custom errors. When throw statement is executed, the statements present
after it will not execute. The control will directly pass to the catch block.
<html>
<head>Exception Handling</head>
<body>
<script>
try {
throw new Error('This is the throw keyword'); //user-defined throw statement.
}
catch (e) {
document.write(e.message); // This will generate an error message
}
</script>
</body>
</html>

Q.9) How to Use JavaScript Date Methods explain?


 The date object supports numerous date methods, but for this article, we only need the current
date and will only use three methods:
 getFullYear() – we will use this method to get the year as a four digit number (yyyy), for
example 2022.
 getMonth() – This gets the month as a number (0-11), for example 2 for March since it‟s a zero
based index (meaning it starts from 0).
 getDate() – gets the day as a number (1-31).
 Let’s now put all these together based on the format in which we want our date to appear:
const date = new Date();
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
// This arrangement can be altered based on how we want the date's format to appear.
let currentDate = `${day}-${month}-${year}`;
console.log(currentDate); // "17-6-2022"
 Current Time in JavaScript: Use the following script to get the current time using JavaScript in
“H:i:s” format.
today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
getHours() – Provides current hour between 0-23.
getMinutes() – Provides current minutes between 0-59.
getSeconds() – Provides current seconds between 0-59.
 Use the following script to get the current date and time using JavaScript in the “Y-m-d
H:i:s” format. You can simply combine the output of the above JavaScript code in one variable as
below:
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
console.log(dateTime)

Q.10) Explain JavaScript Math object?


 The JavaScript math object provides several constants and methods to perform mathematical
operation. Unlike date object, it doesn't have constructors. In JavaScript, Math is a built-in object
that allows you to perform mathematical operations on the Number type. Math is not a constructor
function. It's a property of the implicit global object. You can access methods and constants of
the Math object directly. For example, to use the mathematical PI constant, use Math.PI in your

More Group’s Page 5


code.
 JavaScript Math Methods: Let's see the list of JavaScript Math methods with description.
Methods Description
log() It returns natural logarithm of a number.
trunc() It returns an integer part of the given number.
sqrt() It returns the square root of the given number
tan() It returns the tangent of the given number.
 Math.sqrt(n): The JavaScript math.sqrt(n) method returns the square root of the given number.
Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>
Output: Square Root of 17 is: 4.123105625617661
 JavaScript Number Methods: Let's see the list of JavaScript number methods with their
description.
Methods Description
isFinite() It determines whether the given value is a finite number.
isInteger() It determines whether the given value is an integer.
toPrecision() It returns the string representing a number of specified precision.
toString() It returns the given number in the form of string.
 JavaScript Boolean: JavaScript Boolean is an object that represents value in two
states: true or false. You can create the JavaScript Boolean object by Boolean() constructor as
given below. Boolean b=new Boolean(value); The default value of JavaScript Boolean object
is false.
JavaScript Boolean Example:
<script> document.write(10<20); //true
document.write(10<5); //false
</script>

Q.11) What is regular expression in JS, Explain with syntax?


 A regular expression is a sequence of characters that forms a search pattern. The search pattern
can be used for text search and text to replace operations. A regular expression can be a single
character or a more complicated pattern. Regular expressions can be used to perform all types of
text search and text replacement operations. The RegExp Object is a regular expression with
added Properties and Methods.
 Syntax: /pattern/modifiers;
 Example: let patt = /I AM AI & DS Student/i;
 Explanation: I AM AI & DS Student/i is a regular expression. I AM AI & DS Student is the
pattern (to be used in a search). I is a modifier (modifies the search to be Case-Insensitive).
 Modifiers: Modifiers are used to perform case-insensitive and global searches:
Modifier Description
g Perform a global match (find all matches rather than stopping after the first match)
i Perform case-insensitive matching
m Perform multiline matching

 Brackets: Brackets are used to find a range of characters:.


Expression Description
[abc] Find any character between the brackets
[^abc] Find any character NOT between the brackets
[0-9] Find any character between the brackets (any digit)
[^0-9] Find any character NOT between the brackets (any non-digit)
(x|y) Find any of the alternatives specified
 Metacharacters: Metacharacters are characters with a special meaning:

More Group’s Page 6


Metacharacter Description
. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word, beginning like this: \bHI, end
like this: HI\b
\B Find a match, but not at the beginning/end of a word
\0 Find a NULL character
\n Find a new line character
\f Find a form feed character
\r Find a carriage return character
\t Find a tab character
\v Find a vertical tab character
\xxx Find the character specified by an octal number xxx
 Quantifiers:
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
?=n Matches any string that is followed by a specific string n
?!n Matches any string that is not followed by a specific string n
 RegExp Object Properties:
Property Description
constructor Returns the function that created the RegExp object's prototype
global Checks whether the "g" modifier is set
ignoreCase Checks whether the "i" modifier is set
lastIndex Specifies the index at which to start the next match
multiline Checks whether the "m" modifier is set
source Returns the text of the RegExp pattern
 RegExp Object Methods:
Method Description
compile() Deprecated in version 1.5. Compiles a regular expression
exec() Tests for a match in a string. Returns the first match
test() Tests for a match in a string. Returns true or false
toString() Returns the string value of the regular expression

Q.12) Describe Timing Events & async/await function in JavaScript?


 Timing Events: The window object allows execution of code at specified time intervals. These
time intervals are called timing events. The two key methods to use with JavaScript are:
 setTimeout(function, milliseconds). Executes a function, after waiting a specified number of

More Group’s Page 7


milliseconds. setInterval(function, milliseconds).
 Same as setTimeout(), but repeats the execution of the function continuously.
 The setTimeout() and setInterval() are both methods of the HTML DOM Window object.
 Timing Events: Stop the Execution: The clearTimeout() method stops the execution of the
function specified in setTimeout(). window.clearTimeout(timeoutVariable)
Example:
myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);
 Javscript async/await: We use the async keyword with a function to represent that the function
is an asynchronous function. The async function returns a promise. The syntax of async function
is:
async function name(parameter1, parameter2, ...paramaterN) { // statements }
 Here, name: name of the function. Parameters: parameters that are passed to the function
 Here is how to use the Promise:
myFunction().then
(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
o Await Syntax: The await keyword can only be used inside an async function. The await keyword
makes the function pause the execution and wait for a resolved promise before it continues:
let value = await promise;
Basic Syntax :
async function myDisplay() {
let myPromise = new Promise(function(resolve, reject) {
resolve("I love You !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();

(PPT Give you more understanding than PDF) The material for the PDF has been compiled from various sources such as books, tutorials
(offline and online), lecture notes, several resources available on Internet. The information contained in this PDF is for general information
and education purpose only. While we endeavor to keep the information up to date and correct, we make no representation of any kind
about the completeness and accuracy of the material. The information shared through this PDF material should be used for educational
purpose only.

More Group’s Page 8


Assignment-5

Q.1) What is Nodejs? Explain it's 5 uses?


 Node.js is a runtime environment that allows you to run JavaScript code on the server side. It uses
the V8 JavaScript engine, developed by Google, which executes JavaScript code outside of a web
browser. Node.js provides an event-driven, non-blocking I/O model that makes it lightweight and
efficient, perfect for building scalable and real-time applications.
 Here are five common uses of Node.js:
o Web Development: Node.js is widely used for building web applications and APIs. Its event-
driven architecture and non-blocking I/O make it suitable for handling numerous concurrent
connections. Popular frameworks like Express.js are often used in conjunction with Node.js to
simplify web development tasks.
o Real-time Applications: Node.js is well-suited for building real-time applications like chat
applications, online gaming platforms, collaborative tools, and live-tracking applications. Its
event-driven architecture allows for handling multiple client requests simultaneously, making it
ideal for applications that require instant data updates.
o Microservices: Node.js is commonly used in microservices architectures due to its lightweight
nature and scalability. Developers can build independent, smaller services that communicate with
each other, allowing for easier maintenance and scaling of complex applications.
o Command Line Tools: Node.js can be utilized to create command-line tools and scripts, making
it a versatile choice for automating repetitive tasks, system administration, and development
workflows. Packages like Commander.js and yargs simplify the process of building command-
line interfaces.
o IoT (Internet of Things): Node.js can be used in IoT applications due to its lightweight footprint
and ability to handle asynchronous operations effectively. It can manage devices, collect data
from sensors, and interact with hardware, making it suitable for developing IoT solutions.

Q.2) Why do we use Nodejs? How it handle request?


 A common task for a web server can be to open a file on the server and return the content to
the client. Here is how PHP or ASP handles a file request:
o Sends the task to the computer's file system.
o Waits while the file system opens and reads the file.
o Returns the content to the client.
o Ready to handle the next request.
 Here is how Node.js handles a file request:
o Sends the task to the computer's file system.
o Ready to handle the next request.
o When the file system has opened and read the file, the server returns the content to the client.
o Node.js eliminates the waiting, and simply continues with the next request.
o Node.js runs single-threaded, non-blocking, asynchronous programming, which is very memory
efficient.

Q.3) What Nodejs can perform? Write about command line interface?
 Node.js can Perform:
o Node.js can generate dynamic page content
o Node.js can create, open, read, write, delete, and close files on the server
o Node.js can collect form data
o Node.js can add, delete, modify data in your database
 Node.js File means:
o Node.js files contain tasks that will be executed on certain events
o A typical event is someone trying to access a port on the server
o Node.js files must be initiated on the server before having any effect
o Node.js files have extension ".js"
 Command Line Interface: Node.js files must be initiated in the "Command Line Interface"

More Group’s Page 1


program of your computer. How to open the command line interface on your computer depends
on the operating system. For Windows users, press the start button and look for "Command
Prompt", or simply write "cmd" in the search field.

Q.4) Explain Nodejs process model? Explain with diagram?


 Node.js Process Model: In the
traditional web server model,
each request is handled by a
dedicated thread from the thread
pool. If no thread is available in
the thread pool at any point of
time then the request waits till
the next available thread.
Dedicated thread executes a
particular request and does not
return to thread pool until it
completes the execution and
returns a response.
o Node.js processes user requests differently when compared to a traditional web server model.
Node.js runs in a single process and the application code runs in a single thread and thereby needs
less resources than other platforms.
o All the user requests to your web application will be handled by a single thread and all the I/O
work or long running job is performed asynchronously for a particular request.
o So, this single thread doesn't have to wait for the request to complete and is free to handle the next
request. When asynchronous I/O work completes then it processes the request further and sends
the response
o The following figure illustrates asynchronous web server model using Node.js:

o Node.js process model increases the performance and scalability with a few caveats. Node.js is
not fit for an application which performs CPU-intensive operations like image processing or other
heavy computation work because it takes time to process a request and thereby blocks the single
thread.
o Contrary to the traditional web server model, NodeJS uses an event-driven, non-blocking I/O
model that makes it lightweight and efficient. The NodeJS process model can be explained with
three architectural features of NodeJS.

Q.5) What is Nodejs module? Explain any 2 module in details?


 Node.js Module: Module in Node.js is a simple or complex functionality organized in single or
multiple JavaScript files which can be reused throughout the Node.js application. Each module in
Node.js has its own context, so it cannot interfere with other modules or pollute global scope.
Also, each module can be placed in a separate .js file under a separate folder. Node.js
implements CommonJS modules standard. CommonJS is a group of volunteers who define
JavaScript standards for web server, desktop, and console application. Node.js includes three
types of modules: Core Modules, Local Modules, Third Party Modules.

More Group’s Page 2


 Node.js Modules: Node.js is a light weight framework. The core modules include bare minimum
functionalities of Node.js. These core modules are compiled into its binary distribution and load
automatically when Node.js process starts. However, you need to import the core module first in
order to use it in your application.
Module Description
http http module includes classes, methods and events to create Node.js http server.
url url module includes methods for URL resolution and parsing.
querystring querystring module includes methods to deal with query string.
path path module includes methods to deal with file paths.
fs fs module includes classes, methods, and events to work with file I/O.
util util module includes utility functions useful for programmers.

Q.6) What file system in Nodejs? Explain it's operation in detail?


 In Node.js, the File System (FS) module provides a way to interact with the computer's file
system. It allows you to perform various operations on files and directories, such as creating,
reading, updating, deleting, and renaming. The FS module is built on asynchronous functions,
which means that operations are performed in a non-blocking manner, allowing your code to
continue executing while the operation is in progress.
 The "file system" generally refers to the module named fs (short for "file system"). This module
provides an API for interacting with the file system in a Node.js application. It allows you to
perform various operations on files, directories, and other file-related tasks.
 The “fs” module includes methods to perform both synchronous and asynchronous operations.
Some of the commonly used operations include:
 File Operations:
o Reading files: fs.readFile(), fs.readFileSync()
o Writing files: fs.writeFile(), fs.writeFileSync()
o Deleting files: fs.unlink(), fs.unlinkSync()
o Renaming files: fs.rename(), fs.renameSync()
o Checking file existence: fs.existsSync()
 Directory Operations:
o Creating directories: fs.mkdir(), fs.mkdirSync()
o Reading directories: fs.readdir(), fs.readdirSync()
o Removing directories: fs.rmdir(), fs.rmdirSync()
 The file system operations provided by the fs module are essentially abstractions over underlying
system calls provided by the operating system. When you perform a file system operation in
Node.js using fs, it interacts with the operating system to execute these low-level system calls.
 Internally, Node.js leverages the system's native capabilities to perform file-related tasks. For
instance, when you read from a file using fs.readFile(), Node.js internally makes system calls to
the operating system's file I/O functions to retrieve the data from the specified file.

Q.7) Describe database in Nodejs & Explain?


A. Database connectivity: Database connectivity in Node.js involves establishing a connection
between a Node.js application and a database server. This connection allows the application to
perform various operations on the database, such as reading, writing, updating, and deleting data.
There are several popular database drivers available for Node.js, including:
 MySQL: A relational database management system (RDBMS) that stores data in tables with rows
and columns.
 MongoDB: A NoSQL database that stores data in JSON-like documents.
 PostgreSQL: An open-source RDBMS known for its reliability and performance.
 Redis: An in-memory data store that provides high-speed caching and data access.

B. Connection string: A connection string is a string of text that contains the necessary information
to connect to a database server. It typically includes the following elements:
 Hostname: The IP address or domain name of the database server.

More Group’s Page 3


 Port: The port number that the database server is listening on.
 Database name: The name of the database to connect to.
 Username: The username to connect to the database with.
 Password: The password for the database username.
 For example, a connection string for a MySQL database might look like this:
mysql://username:password@hostname:port/database_name

C. Database operation: Once a connection to the database is established, Node.js applications can
perform various operations on the data. These operations can be broadly categorized into the
following types:
 Creating: Inserting new data into the database.
 Reading: Retrieving existing data from the database.
 Updating: Modifying existing data in the database.
 Deleting: Removing data from the database.
 These operations are typically performed using the database driver's API, which provides methods
for each type of operation. For example, to create a new user in a MySQL database, you might
use the following code:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
database: 'mydatabase',
user: 'root',
password: 'password'
});
connection.connect(err => {
if (err) throw err;
const sql = 'INSERT INTO users (username, email) VALUES (?, ?)';
const values = ['johndoe', 'johndoe@example.com'];
connection.query(sql, values, (err, result) => {
if (err) throw err;
console.log('User created successfully');
});
connection.end();
});
This code connects to a MySQL database, creates a new user record, and then closes the
connection.

Q.8) Write Short note on MERN?


 MERN Stack is a JavaScript Stack
that is used for easier and faster
deployment of full-stack web
applications. MERN Stack
comprises of 4 technologies
namely: MongoDB, Express, React
and Node.js. It is designed to make
the development process smoother
and easier.
o MongoDB: Non Relational
Database
o Express: Node.js web server
o React: JavaScript Frontend
Framework
o Node: JavaScript Web Server

More Group’s Page 4


 How MERN stack works: When working with MERN stack, developers create implement View
layer using React and Express and Node are used to implement application layer of website then
MongoDB is used to implement database layer.
 Roadmap to become a MERN Stack Developer:
o Step 1: Learn basics of HTML, CSS and JavaScript
o Step 2: Learn React which is a frontend library for building User Interfaces
o Step 3: Learn Node.js which is JavaScript runtime environment
o Step 4: Learn Express.js, a framework built upon Node.js to simplify the process of creating web
application and API building.
o Step 5: Learn MongoDB, a NoSQL database to store and retrieve data from database.

(PPT Give you more understanding than PDF) The material for the PDF has been compiled from various sources such as books, tutorials
(offline and online), lecture notes, several resources available on Internet. The information contained in this PDF is for general information
and education purpose only. While we endeavor to keep the information up to date and correct, we make no representation of any kind
about the completeness and accuracy of the material. The information shared through this PDF material should be used for educational
purpose only.

More Group’s Page 5

You might also like