Professional Documents
Culture Documents
FSD Week 4
FSD Week 4
HTML
• TML stands for Hyper Text Markup Language
• HTML is the standard markup language for creating Web pages
• HTML describes the structure of a Web page
• HTML consists of a series of elements
• HTML elements tell the browser how to display the content
• HTML elements label pieces of content such as "this is a heading", "this is a paragraph", "this
is a link", etc.
Example Explained
• The <!DOCTYPE html> declaration defines that this document is an HTML5 document
• The <html> element is the root element of an HTML page
• The <head> element contains meta information about the HTML page
• The <title> element specifies a title for the HTML page (which is shown in the browser's title
bar or in the page's tab)
• The <body> element defines the document's body, and is a container for all the visible
contents, such as headings, paragraphs, images, hyperlinks, tables, lists, etc.
• The <h1> element defines a large heading
• The <p> element defines a paragraph
The HTML element is everything from the start tag to the end tag:
<h1>My First Heading</h1>
<p>My first paragraph.</p>
JB PORTALS 1
FULL STACK DEVELOPMENT - WEEK 4
Web Browsers
The purpose of a web browser (Chrome, Edge, Firefox, Safari) is to read HTML documents
and display them correctly.
A browser does not display the HTML tags, but uses them to determine how to display the
document:
CSS
CSS stands for Cascading Style Sheets. CSS describes how HTML elements are to be displayed
on screen, paper, or in other media. CSS saves a lot of work. It can control the layout of
multiple web pages all at once. External stylesheets are stored in CSS files
JB PORTALS 2
FULL STACK DEVELOPMENT - WEEK 4
CSS Example
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p{
font-family: verdana;
font-size: 20px;
}
When tags like <font>, and color attributes were added to the HTML 3.2 specification,
it started a nightmare for web developers. Development of large websites, where fonts and
color information were added to every single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
CSS removed the style formatting from the HTML page!
CSS Syntax
The selector points to the HTML element you want to style. The declaration block
contains one or more declarations separated by semicolons. Each declaration includes a CSS
property name and a value, separated by a colon. Multiple CSS declarations are separated
with semicolons, and declaration blocks are surrounded by curly braces.
JB PORTALS 3
FULL STACK DEVELOPMENT - WEEK 4
Example
In this example all <p> elements will be center-aligned, with a red text color:
p{
color: red;
text-align: center;
}
• p is a selector in CSS (it points to the HTML element you want to style: <p>).
• color is a property, and red is the property value
• text-align is a property, and center is the property value
CSS Selectors
CSS selectors are used to "find" (or select) the HTML elements you want to style. We can
divide CSS selectors into five categories:
• Simple selectors (select elements based on name, id, class)
• Combinator selectors (select elements based on a specific relationship between them)
• Pseudo-class selectors (select elements based on a certain state)
• Pseudo-elements selectors (select and style a part of an element)
• Attribute selectors (select elements based on an attribute or attribute value)
This page will explain the most basic CSS selectors.
JB PORTALS 4
FULL STACK DEVELOPMENT - WEEK 4
Example
In this example all HTML elements with class="center" will be red and center-aligned:
.center {
text-align: center;
color: red;
}
You can also specify that only specific HTML elements should be affected by a class.
Example
In this example only <p> elements with class="center" will be red and center-aligned:
p.center {
text-align: center;
color: red;
}
HTML elements can also refer to more than one class.
Example
In this example the <p> element will be styled according to class="center" and to
class="large":
<p class="center large">This paragraph refers to two classes.</p>
JB PORTALS 5
FULL STACK DEVELOPMENT - WEEK 4
JavaScript
JavaScript Fundamentals
• Writing JavaScript code in an HTML page: We must enclose the JavaScript code within the
<script> tag in order to include it on an HTML page just as the example shown below:
<script type = "text/javascript">
//JavaScript coding can be done inside this tag
</script>
With this information, the browser can correctly make out that the code is written in
JavaScript and execute the code.
Inclusion of external JavaScript files in an HTML file: An external JavaScript file can also
be written separately and included within our HTML file. That way, different types of code
can be kept isolated from one another, resulting in better-organised files. For instance, if our
JavaScript code is written in the file script.js, we can include it in our HTML file in the
following way:
<script src="script.js"></script>
JavaScript | Statements
The programming instructions written in a program in a programming language are
known as statements.
Order of execution of Statements is the same as they are written.
1. Semicolons:
o Semicolons separate JavaScript statements.
o Semicolon marks the end of a statement in javascript.
o Multiple statements on one line are allowed if they are separated with a semicolon.
a=2;b=3;z=a+b;
2. Code Blocks:
JavaScript statements can be grouped together inside curly brackets. Such groups are
known as code blocks. The purpose of grouping is to define statements to be executed
together. Example functions.
3. White Space:
Javascript ignores multiple white spaces. Javascript would treat following 2 statements as
same:
Example:
var a="Hello Geek";
var a = "Hello Geek";
JB PORTALS 6
FULL STACK DEVELOPMENT - WEEK 4
4. Line Length and Line Breaks: Javascript code preferred line length by most
programmers is upto 80 characters. The best place to break a code line in Javascript, if it
doesn’t fits, is after an operator.
Example:
document.getElementById("geek1").innerHTML =
"Hello Geek!";
5.Keywords:
Keywords are reserved words and cannot be used as variable name. A Javascript
keyword tells about what kind of operation it will perform.
JavaScript Comment
The JavaScript comments are meaningful way to deliver message. It is used to add
information about the code, warnings or suggestions so that end user can easily interpret
the code. The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the
browser.
Types of JavaScript Comments
There are two types of comments in JavaScript.
1. Single-line Comment
2. Multi-line Comment
JavaScript Single line Comment
It is represented by double forward slashes (//). It can be used before and after the
statement. Let’s see the example of single-line comment i.e. added before the statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>
JB PORTALS 7
FULL STACK DEVELOPMENT - WEEK 4
2. Javascript Variables
Variables in JavaScript are simply names of storage locations. In other words, they can be
considered as stand-in values that we can use to perform various operations in our
JavaScript codes. JavaScript allows the usage of variables in the following three ways:
•
• var: The most commonly used variable in JavaScript is var. It can be redeclared and its value
can be reassigned, but only inside the context of a function. When the JavaScript code is run,
variables defined using var are moved to the top. An example of a variable declared using the
"var" keyword in JavaScript is shown below:
var x = 140; // variable x can be reassigned a new value and also redeclared
• const: const variables in JavaScript cannot be used before they appear in the code. They can
neither be reassigned values, that is, their value remains fixed throughout the execution of
the code, nor can they be redeclared. An example of a variable declared using the "const"
keyword in JavaScript is shown below:
const x = 5; // variable x cannot be reassigned a new value or redeclared
• let: The let variable, like const, cannot be redeclared. But they can be reassigned a value. An
example of a variable declared using the "let" keyword in JavaScript is shown below:
let x = 202; // variable x cannot be redeclared but can be reassigned a new value
JB PORTALS 8
FULL STACK DEVELOPMENT - WEEK 4
• Variables: The variable data type, as the name suggests, does not have a fixed value. An
example of the variables data type is shown below: var y
• Text (strings): String data types of JavaScript are a combination of multiple characters. An
example of the string data type is shown below: var demoString = "Hello World"
• Operations: Operations in JavaScript can also be assigned to JavaScript variables. An
example of these is shown below: var sum = 20 + 30 + 29
• Boolean values: Boolean values can be true or false. An example of the boolean data type is
shown below: var booleanValue = true
• Constant numbers: As the name suggests, these data types have a fixed value. An example
of the constant data type is shown below: const g = 9.8
• Objects: JavaScript objects are containers for named values called properties. They possess
their own data members and methods. An example of the objects data type is shown below:
var name = {name:"Jon Snow", id:"AS123"}
JavaScript Operators
You can use variables to conduct a variety of tasks using JavaScript operators. The
various types of operators in JavaScript are as follows:
• Fundamental Operators: These operators are used to perform basic operations like
addition, multiplication, etc. in JavaScript. A list of all the Fundamental operators in
JavaScript is as follows:
o +: The Addition Operator is used to add two numbers
o -: The Subtraction Operator is used to subtract two numbers
o *: The MultiplicationOperator is used to multiply two numbers
o /: The Division Operator is used to divide two numbers
o (...): In general, operations within brackets are executed earlier than that outside. This
grouping operator surrounds an expression or sub-expression with a pair of parentheses to
override the conventional operator precedence, allowing operators with lower precedence
to be evaluated before operators with higher precedence. It does exactly what it says: it
groups the contents of the parentheses.
JB PORTALS 9
FULL STACK DEVELOPMENT - WEEK 4
o %: The Modulus operator is used to get the remainder when an integer number is divided by
another integer number.
o ++: The Increment operator is used to increase the value of numbers by one.
o --: The Decrement operator is used to decrease the value of numbers by one.
o ||: If and only if one or more of its operands are true, the logical OR operator (logical
disjunction) is true for a set of operands. It's most often used with logical (Boolean) values.
It returns a Boolean value when this is the case. The || operator, on the other hand, returns
the value of one of the provided operands, hence using it with non-Boolean values will result
in an error.
o !: The logical NOT operator (logical complement, negation) converts truth to falsity. It's most
commonly used with logical (Boolean) values. It returns false if its sole operand can be
transformed to true when used with non-Boolean values; otherwise, it returns true.
JB PORTALS 10
FULL STACK DEVELOPMENT - WEEK 4
Control Flow
JavaScript If-Else Statements
The if-else statements are simple to comprehend. You can use them to set conditions
for when your code runs. If specific requirements are met, something is done; if they are not
met, another action is taken. The switch statement is a concept that is comparable to if-else.
The switch however allows you to choose which of several code blocks to run. The syntax of
if-else statements in JavaScript is given below:
if (check condition) {
// block of code to be executed if the given condition is satisfied
} else {
// block of code to be executed if the given condition is not satisfied
}
Loops in JavaScript:
Most programming languages include loops. They let you run code blocks as many
times as you like with different values. Loops can be created in a variety of ways in JavaScript:
• the for loop: The most frequent method of creating a loop in JavaScript. Its syntax is shown
below:
for (initialization of the loop variable; condition checking for the loop;
updation after the loop) {
// code to be executed in loop
}
• the while loop: Establishes the conditions under which a loop will run. Its syntax is shown
below:
// Initialization of the loop variable is done before the while loop begins
while(condition checking for the loop){
// 1. code to be executed in loop
// 2. updation of the loop variable
• the do-while loop: Similar to the while loop, but it runs at least once and checks at the end to
see whether the condition is met to run again. Its syntax is shown below:
// Initialization of the loop variable is done before the do-while loop begins
do{
// 1. code to be executed in loop
// 2. updation of the loop variable
}while(condition checking for the loop);
There are two statements that are important in the context of loops:
• the continue statement: Skip parts of the loop if certain conditions are met.
• break statement: Used to stop and exit the cycle when specific conditions are met.
JB PORTALS 11
FULL STACK DEVELOPMENT - WEEK 4
JavaScript Functions
JavaScript Functions can be defined as chunks of code written in JavaScript to perform a
single task. A function in JavaScript looks like this:
function Function_Name(parameter 1, parameter 2,....,parameterN)
{
// Job or Task of the function
}
The code above consists of the "function" keyword and a name, as you can see. The
parameters of the function are enclosed in brackets, while the function's task code and
output is enclosed in curly brackets. You can make your own, but there are a few default
functions to make your life easier.
Step 2 : Download the Visual Studio Code installer for Windows. Once it is
downloaded, run the installer (VSCodeUserSetup-{version}.exe). Then, run the
file – it will only take a minute.
JB PORTALS 12
FULL STACK DEVELOPMENT - WEEK 4
• After accepting all the requests press finish button. By default, VS Code installs under:
"C:\users{username}\AppData\Local\Programs\Microsoft VS Code."
JB PORTALS 13
FULL STACK DEVELOPMENT - WEEK 4
This will show you a list of the most popular VS Code extensions on the VS Code Marketplace.
Install an extension
To install an extension, select the Install button. Once the installation is complete, the Install
button will change to the Manage gear button.
JB PORTALS 14
FULL STACK DEVELOPMENT - WEEK 4
In the Extensions view (Ctrl+Shift+X), type 'todo' in the search box to filter the
Marketplace offerings to extensions with 'todo' in the title or metadata. You should see the
TODO Highlight extension in the list.
An extension is uniquely identified by its publisher and extension IDs. If you select
the TODO Highlight extension, you will see the Extension details page, where you can find
the extension ID, in this case, wayou.vscode-todo-highlight. Knowing the extension ID can be
helpful if there are several similarly named extensions.
Select the Install button, and VS Code will download and install the extension from
the Marketplace. When the installation is complete, the Install button will be replaced with
a Manage gear button.
JB PORTALS 15
FULL STACK DEVELOPMENT - WEEK 4
To see the TODO Highlight extension in action, open any source code file and add the
text 'TODO:' and you will see the text highlighted. The TODO Highlight extension contributes
the commands, TODO-Highlight: List highlighted annotations and TODO-Highlight: Toggle
highlight, that you can find in the Command Palette (Ctrl+Shift+P). The TODO-Highlight:
Toggle highlight command lets you quickly disable or enable highlighting.
The extension also provides settings for tuning its behavior, which you can find in the
Settings editor (Ctrl+,). For example, you might want the text search to be case insensitive
and you can uncheck the Todohighlight: Is Case Sensitive setting.
If an extension doesn't provide the functionality you want, you can always Uninstall
the extension from the Manage button context menu.
JB PORTALS 16
FULL STACK DEVELOPMENT - WEEK 4
This has been just one example of how to install and use an extension. The VS Code
Marketplace has thousands of extensions supporting hundreds of programming languages
and tasks. Everything from full featured language support for Java, Python, Go, and C++ to
simple extensions that create GUIDs, change the color theme, or add virtual pets to the editor.
Extension details
On the extension details page, you can read the extension's README and review the
extension's:
• Feature Contributions - The extension's additions to VS Code such as settings, commands
and keyboard shortcuts, language grammars, debugger, etc.
• Changelog - The extension repository CHANGELOG if available.
• Dependencies - Lists if the extension depends on any other extensions.
If an extension is an Extension Pack, the Extension Pack section will display which
extensions will be installed when you install the pack. Extension Packs bundle separate
extensions together so they can be easily installed at one time.
JB PORTALS 17
FULL STACK DEVELOPMENT - WEEK 4
You can sort the extension list by Install Count or Rating in either ascending or
descending order. You can learn more about extension search filters below. You can run
additional Extensions view commands via the ... View and More Actions button.
Through this context menu you can control extension updates, enable or disable all
extensions, and use the Extension Bisect utility to isolate problematic extension behavior.
JB PORTALS 18
FULL STACK DEVELOPMENT - WEEK 4
Objects in Javascript
Objects, in JavaScript, are the most important data type and form the building blocks
for modern JavaScript. These objects are quite different from JavaScript’s primitive data
types (Number, String, Boolean, null, undefined, and symbol) in the sense that these
primitive data types all store a single value each (depending on their types).
Syntax:
let object_name = {
key_name : value,
...
}
Let us look at an example of a JavaScript Object below :
<script>
// JavaScript code demonstrating a simple object
let school = {
name: 'Vivekananda School',
location : 'Delhi',
established : '1971',
displayInfo : function(){
console.log(`${school.name} was established
in ${school.established} at ${school.location}`);
}
}
school.displayInfo();
</script>
JB PORTALS 19
FULL STACK DEVELOPMENT - WEEK 4
In this example “name”, “location”, and “established” are all “keys” and
“Vivekananda School”, “Delhi” and 1971 are values of these keys respectively. Each of
these keys is referred to as properties of the object. An object in JavaScript may also have a
function as a member, in which case it will be known as a method of that object.
Here “displayinfo” is a method of the school object that is being used to work with the
object’s data, stored in its properties.
Methods:
Object Methods in JavaScript can be accessed by using functions. Functions in JavaScript are
stored as property values. The objects can also be called without using bracket ().
Properties: A function may be divided into different property values, which are then
combined and returned together.
For Ex: Student function contains the properties:
name
• class
• section
Return Value: It returns methods/functions stored as object properties.
<body>
<h1>Geeks</h1>
<h3>JavaScript Object Method</h3>
<p>
studentDetail is a function definition,
it is stored as a property value.
</p>
<p id="gfg"></p>
JB PORTALS 20
FULL STACK DEVELOPMENT - WEEK 4
<script>
// Object creation
var student = {
name: "Martin",
class : "12th",
section : "A",
studentDetails : function() {
return this.name + " " + this.class
+ " " + this.section + " ";
}
};
// Display object data
document.getElementById("gfg").innerHTML
= student.studentDetails();
</script>
</body>
</html>
Constructors
Class: In JavaScript, a class is a kind of function. This classes are similar to normal java
classes. The classes are declared with the class keyword like another OOP languages. The
class syntax has two components: class declarations and class expressions.
Class declarations:
class GFG {
constructor(A, B, C) {
this.g = A;
this.f = B;
this.gg = C;
}
}
Here class name is GFG.
Class expressions:
<script>
class GFG {
constructor(A, B) {
JB PORTALS 21
FULL STACK DEVELOPMENT - WEEK 4
this.g = A;
this.f = B;
}
print() {
document.write(this.g +"<br>"+this.f);
}
}
let gg = new GFG("JavaScript", "Java");
gg.print();
</script>
this keyword: The this keyword refers to the object it belongs to, like OOPs languages C++,
C#, JAVA etc. this keyword is used in different ways in different areas. While executing a
function in JavaScript that has a reference to its current execution context, that is the
reference by which the function or data member is called.
Adding property to an object: The property can be added to the object by using dot(.)
operator or square bracket.,
var GFG = {
articles: 'computer science',
quantity: 3000,
};
The GFG has two properties “articles” and “quantity”. Now we wish to add one more
property name called subject.
• Using dot (.) operator
GFG.subject: 'JavaScript';
• Using square bracket:
GFG['subject']: 'JavaScript';
Here, subject is the property and ‘JavaScript’ is the value of the property.
JB PORTALS 22
FULL STACK DEVELOPMENT - WEEK 4
Object Properties
Object properties are defined as a simple association between name and value. All
properties have a name and value is one of the attributes linked with the property, which
defines the access granted to the property. Properties refer to the collection of values which
are associated with the JavaScript object. This collection may not follow any particular order.
JavaScript provides the feature to add, delete and modify the properties. Properties are
denoted by name:values pairs.
Syntax:
• objectName.property
• objectName["property"]
• objectName[expression]
Properties:
• addition: It can add new objects by simply giving values to those new objects.
• deletion: It uses delete keyword, to delete a property from an object.
1) Data properties
A data property contains a single location for a data value. A data property has four
attributes:
• [[Configurarable]] – determines whether a property can be redefined or removed via delete
operator.
• [[Enumerable]] – indicates if a property can be returned in the for...in loop.
• [[Writable]] – specifies that the value of a property can be changed.
• [[Value]] – contains the actual value of a property.
The following example creates a person object with two properties firstName and
lastName with the configurable, enumerable, and writable attributes set to true. And their
values are set to 'John' and 'Doe' respectively:
let person = {
firstName: 'John',
lastName: 'Doe'
};
JB PORTALS 23
FULL STACK DEVELOPMENT - WEEK 4
The following example creates a person object with the age property:
let person = {};
person.age = 25;
Code language: JavaScript (javascript)
Since the default value of the [[Configurable]] attribute is set to true, you can remove
it via the delete operator:
delete person.age;
console.log(person.age);
Code language: CSS (css)
Output:
undefined
There are two keywords which define the accessors functions: a getter and setter for
the fullName property. When the property is accessed, the return value from the getter is
used. When a value is set, the setter is called and passed the value that was set.
When you read data from an accessor property, the [[Get]] function is called
automatically to return a value. The default return value of the [[Get]] function is undefined.
If you assign a value to an accessor property, the [[Set]] function is called automatically. To
define an accessor property, you must use the Object.defineProperty() method. or example:
let person = {
firstName: 'John',
lastName: 'Doe'
}
Object.defineProperty(person, 'fullName', {
get: function () {
return this.firstName + ' ' + this.lastName;
},
set: function (value) {
let parts = value.split(' ');
if (parts.length == 2) {
this.firstName = parts[0];
JB PORTALS 24
FULL STACK DEVELOPMENT - WEEK 4
this.lastName = parts[1];
} else {
throw 'Invalid name format';
}
}
});
console.log(person.fullName);
Output:
'John Doe'
In this example:
• First, define the person object that contains two properties: firstName and lastName.
• Then, add the fullName property to the person object as an accessor property.
• If the full name is not in the correct format i.e., first name, space, and last name, it will
throw an error.
Object Prototypes
JavaScript prototypes are used to accessing properties and methods of objects.
Inherited properties are originally defined in the prototype or parent object. The Date object
is inherited from Date.prototype, Array object inherits from Array.prototype etc. The
prototypes may be used to add new properties and methods to the existing objects and object
constructor.
Syntax:
Object.prototype
Example 1: This example adding new property to the object.
<!DOCTYPE html>
<html>
<head>
JB PORTALS 25
FULL STACK DEVELOPMENT - WEEK 4
<title>
JavaScript Object Prototypes
</title>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>JavaScript Object Prototypes</h2>
<p id="GFG"></p>
<script>
function Student(a, b) {
this.name = a;
this.id = b;
}
Student.prototype.age = 12;
var s1 = new Student("Dinesh", 1234567);
document.getElementById("GFG").innerHTML = s1.name +
" is " + s1.age + " years old.";
</script>
</body>
</html>
For example, if we're modeling a school, we might have professors and students: they
are both people, so have some features in common (for example, they both have names), but
each might add extra features (for example, professors have a subject that they teach), or
might implement the same feature in different ways. In an OOP system we might say that
professors and students both inherit from people.
JB PORTALS 26
FULL STACK DEVELOPMENT - WEEK 4
Introduction to ES6
ES6 or ECMAScript 2015 is the 6th version of the ECMAScript programming language.
ECMAScript is the standardization of Javascript which was released in 2015, and
subsequently renamed as ECMAScript 2015. ECMAScript and Javascript are both different in
nature.
ECMAScript vs Javascript
ECMAScript: It is the specification defined in ECMA-262 for creating a general purpose
scripting language.In simple terms it is a standardization for creating a scripting language.It
was introduced by Ecma International, and is basically an implementation with which we
learn how to create a scripting language.
Arrow functions
Arrow functions(also known as ‘fat arrow functions’) are a more concise syntax for
writing function expressions.Introduced in ES6, arrow functions are definitely one of the
most impactful changes in javascript. These function expressions makes your code more
readable, more modern. Arrow functions allow us to write shorter function syntax:
Before
hello = function() {
return "Hello World!";
}
With Arrow Function:
hello = () => {
return "Hello World!";
}
It gets shorter! If the function has only one statement, and the statement returns a value, you
can remove the brackets and the return keyword:
Arrow Functions Return Value by Default:
hello = () => "Hello World!";
Arrow Function With Parameters:
If you have parameters, you pass them inside the parentheses:
hello = (val) => "Hello " + val;
Arrow Function Without Parentheses:
In fact, if you have only one parameter, you can skip the parentheses as well:
hello = val => "Hello " + val;
JB PORTALS 27
FULL STACK DEVELOPMENT - WEEK 4
Template Strings
REFERENCE LINK: https://www.geeksforgeeks.org/what-are-the-template-literals-in-es6/
Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides
an easy way to create multiline strings and perform string interpolation. Template literals
are the string literals and allow embedded expressions.
Before ES6, template literals were called as template strings. Unlike quotes in
strings, template literals are enclosed by the backtick (` `) character. Template literals can
contain placeholders, which are indicated by the dollar sign and curly braces
($(expression}). Inside the backticks, if we want to use an expression, then we can place
that expression in the ($(expression}).
Syntax
var str = `string value`;
We can inject the JavaScript expressions and strings inside it.
Syntax:
`Any string ${str} can appear here`
Example: In this example, we are illustrating a simple demo of template literals.
<script>
const str1 = `Hi, GeeksforGeeks Learner`;
console.log(str1);
const str = "GeeksforGeeks";
const str2 = `Hi, ${str} Learner`;
console.log(str2);
</script>
Prototype Methods
The prototype property allows you to add properties and methods to any object
(Number, Boolean, String and Date, etc.). Use the following syntax to create a Boolean
prototype.
object.prototype.name = value
Example
The following example shows how to use the prototype property to add a property to an
object.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
JB PORTALS 28
FULL STACK DEVELOPMENT - WEEK 4
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Tom");
book.prototype.price = null;
myBook.price = 100;
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
The following output is displayed on successful execution of the above code.
Spread Operator
REFERENCE LINK: https://www.w3schools.com/react/react_es6_spread.asp
https://www.geeksforgeeks.org/es6-spread-operator/
Spread Operator is a very simple and powerful feature introduced in ES6 standard of
JavaScript, which helps us to write nicer and shorter code. The JavaScript spread operator is
denoted by three dots (…). The spread operator helps the iterable objects to expand into
individual elements. Iterable objects are those on which we can use a loop, for example,
Array, Map, Set, etc. In other words, the spread operator allows us to copy all elements from
the existing array or object into another array or object.
Syntax:
var variablename1 = [...value];
Let’s understand the usage of spread operator through following illustrated examples:
<html>
<body>
<script>
const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
JB PORTALS 29
FULL STACK DEVELOPMENT - WEEK 4
</body>
</html>
Assign the first and second items from numbers to variables and put the rest in an array:
<html>
<body>
<script>
const numbers = [1, 2, 3, 4, 5, 6];
const [one, two, ...rest] = numbers;
document.write("<p>" + one + "</p>");
document.write("<p>" + two + "</p>");
document.write("<p>" + rest + "</p>");
</script>
</body>
</html>
Output:
1
2
3,4,5,6
:
JB PORTALS 30
FULL STACK DEVELOPMENT - WEEK 4
}
const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}
//Check the result object in the console:
console.log(myUpdatedVehicle);
</script>
<p>Press F12 and see the result object in the console view.</p>
</body>
</html>
Map
REFERENCE LINK: https://www.tutorialspoint.com/es6/es6_maps_and_sets.htm
https://www.javatpoint.com/es6-
map#:~:text=ES6%20provides%20us%20a%20new,the%20new%20or%20empty%20Ma
p.
A map is an ordered collection of key-value pairs. Maps are similar to objects. However,
there are some differences between maps and objects. When we iterate over the map object
it returns the key, value pair in the same order as inserted. These are listed below −
Syntax
The syntax for Map is given below −
let map = new Map([iterable])
let map = new Map()
Example
The following example creates a map using an iterable constructor −
<script>
let andy = {ename:"Andrel"},
varun = {ename:"Varun"},
prijin = {ename:"Prijin"}
JB PORTALS 31
FULL STACK DEVELOPMENT - WEEK 4
Syntax
Map.size
Example
var map = new Map();
map.set('John', 'author');
map.set('arry', 'publisher');
map.set('Mary', 'subscriber');
map.set('James', 'Distributor');
console.log(map.size);
Output
4
Following are some common methods that can be used to manipulate maps −
Sr.No Object & Map
set(key,value)
1
Adds key and value to map
get(key)
2
Returns value if key is matched
has(key)
3
Returns true if an element with the specified key exists; else returns false
keys()
4
Returns an iterator that contains the keys for each element in the map object
JB PORTALS 32
FULL STACK DEVELOPMENT - WEEK 4
values()
5
Returns an iterator that contains the values for each element in the map object
entries()
6
Returns an iterator that contains the key-value pairs for each element in the Map
delete(key)
7
Removes the specified element from a Map object
Set
A set is a collection of items which are unique i.e no element can be repeated. Set in
ES6 are ordered: elements of the set can be iterated in the insertion order. Set can store any
types of values whether primitive or objects.
Syntax
new Set([iterable])
new Set()
Example
<script>
let names = new Set(['A','B','C','D']);
console.log(names)
</script>
Output:
{"A", "B", "C", "D"}
Checking the size of a set: The size property of the Set object can be used to query the
number of elements in the Set.
Syntax
set.size
Example
<script>
let names = new Set(['A','B','C','D']);
console.log(names.size)
</script>
Output:
4
JB PORTALS 33
FULL STACK DEVELOPMENT - WEEK 4
Iterating a Set
We can use the forEach and for..of loops to iterate through a Set.
Example
<script>
let names= new Set(['A','B','C','D']);
//iterate using forEach
console.log('forEach')
names.forEach(n=>console.log(n))
console.log('for of..')
//iterate using for..of
for(let n of names){
console.log(n)
}
</script>
Output:
forEach
A
B
C
D
for of..
A
B
C
D
add(element)
1
Adds an element to the Set
has(element)
2
Returns true if element found; else returns false
delete(element)
3
Delete specific element from the Set
clear()
4
Clears all elements from the Set
JB PORTALS 34
FULL STACK DEVELOPMENT - WEEK 4
Introduction to TypeScript
TypeScript is an Open Source Object Oriented programming language developed and
maintained by Microsoft Corporation. TypeScript is a strongly typed language and its first
version was introduced in 2012. It is a Strict Super Set of JavaScript, which means anything
that is implemented in JavaScript can be implemented using TypeScript along with the choice
of adding enhanced features (every existing JavaScript Code is a valid TypeScript Code).
2. Class Based Objects – Another huge advantage is the use of Classes which provides the
ability to use true object oriented programming in our applications and prevents use of
prototype based objects. It also provides encapsulation, inheritance and modifiers.
3. ES6 Features – Support for ES6 features is also one of the main reasons for its popularity.
TypeScript Code cannot be interpreted by the Browser directly so there is a need to compile
the TypeScript code into plain JavaScript Code, for this purpose we need the TypeScript
Compiler (tsc).
2. Code quality – Defining data structures in the beginning, using types and interfaces, forces
you to think about your app’s data structure from the start and make better design decisions.
3. Prevents bugs – TypeScript won’t make your software bug free. But it can prevent a lot of
type-related errors. Along with the Clever IntelliSense many browsers and IDEs support
direct debugging through Source Maps .
JB PORTALS 35
FULL STACK DEVELOPMENT - WEEK 4
4. Active community – TypeScript is getting more and more popular. It’s used by the top tech
companies like Google, Airbnb, Shopify, Asana, Adobe, and Mozilla so we can assume that it
reaches their expectations in terms of scalability – as they are developing large and complex
applications.
5. TypeScript Is Just JavaScript – TypeScript starts with JavaScript and ends with JavaScript.
Typescript adopts the basic building blocks of your program from JavaScript. All TypeScript
code is converted into its JavaScript equivalent for the purpose of execution.
Why TypeScript
REFERENCE LINK: https://www.typescripttutorial.net/typescript-tutorial/why-
typescript/
If you use VS Code, you can install the following extension to speed up the development
process:
• Live Server – allows you to launch a development local Server with the hot reload feature.
Install Node.js
To install node.js, you follow these steps:
• Go to the node.js download page.
• Download the node.js version that suits your platform i.e., Windows, macOS, or Linux.
• Execute the downloaded node.js package or execution file. The installation is quite
straightforward.
• Verify the installation by open the terminal on macOS and Linux or command line on
Windows and type the command node -v. If you see the version that you downloaded, then
you have successfully installed the node.js on your computer.
JB PORTALS 36
FULL STACK DEVELOPMENT - WEEK 4
To install the ts-node module globally, you run the following command from the Terminal
on macOS and Linux or Command Prompt on Windows:
npm install -g ts-node
Install VS Code
To install the VS Code, you follow these steps:
• Navigate to the VS Code download page.
• Download the latest version of VS Code that suits your OS (Windows, macOS, or Linux)
• Execute the downloaded package or the installer file to launch the setup wizard. The
installation process is also quite straightforward.
• Launch the VS Code.
You’ll see the VS Code as shown in the following picture:
JB PORTALS 37
FULL STACK DEVELOPMENT - WEEK 4
index.html
<!DOCTYPE html>
<html>
<body>
<h2>Welcome To GFG</h2>
<p>
Default code has been
loaded into the Editor.
</p>
<script src="types.js"></script>
</body>
</html>
types.ts
let myString: string;
myString = 'Hello from ts'
console.log(myString);
On successful compilation a JavaScript file with the same name and .js extension will
be created i.e. types.js containing the transpiled code in the same directory. Now on running
the index.html the below output can be seen. As discussed above TypeScript code is
transpiled into standard JavaScript Code.
JB PORTALS 38
FULL STACK DEVELOPMENT - WEEK 4
Types in TypeScript
TypeScript inherits the built-in types from JavaScript. TypeScript types is categorized into:
• Primitive types
• Object types
Primitive types
The following illustrates the primitive types in TypeScript:
Name Description
Object types
Objec types are functions, arrays, classes, etc. Later, you’ll learn how to create custom object
types.
TypeScript String : Like JavaScript, TypeScript uses double quotes (") or single quotes (') to
surround string literals:
let firstName: string = 'John';
let title: string = "Web Developer";
JB PORTALS 39
FULL STACK DEVELOPMENT - WEEK 4
The template strings allow you to create multi-line strings and provide the string
interpolation features. The following example shows how to create multi-line string using
the backtick (`):
let description = `This TypeScript string can
span multiple
lines `;
String interpolations allow you to embed the variables into the string like this:
let firstName: string = `John`;
let title: string = `Web Developer`;
let profile: string = `I'm ${firstName}. I'm a ${title}`;
console.log(profile);
Output:
I'm John.
I'm a Web Developer.
TypeScript Number
All numbers in TypeScript are either floating-point values or big integers. The
floating-point numbers have the type number while the big integers get the type bigint.
Binary Numbers: The binary number uses a leading zero followed by a lowercase or
uppercase letter “B” e.g., 0b or 0B :
let bin = 0b100;
let anotherBin: number = 0B010;
Note that the digit after 0b or 0B must be 0 or 1.
Octal Numbers : An octal number uses a leading zero followed the letter o (since ES2015)
0o. The digits after 0o are numbers in the range 0 through 7:
let octal: number = 0o10;
JB PORTALS 40
FULL STACK DEVELOPMENT - WEEK 4
Hexadecimal numbers
Hexadecimal numbers use a leading zero followed by a lowercase or uppercase letter X (0x
or 0X). The digits after the 0x must be in the range (0123456789ABCDEF). For example:
let hexadecimal: number = 0XA;
Big Integers
The big integers represent the whole numbers larger than 253 – 1. A Big integer literal has
the n character at the end of an integer literal like this:
let big: bigint = 9007199254740991n;
TypeScript Boolean : The TypeScript boolean type allows two values: true and false. It’s one
of the primitive types in TypeScript.
let pending: boolean;
pending = true;
// after a while
// ..
pending = false;
JavaScript has the Boolean type that refers to the non-primitive boxed object. The Boolean
type has the letter B in uppercase, which is different from the boolean type. It’s a good
practice to avoid using the Boolean type.
JB PORTALS 41
FULL STACK DEVELOPMENT - WEEK 4
When you extract an element from the array, TypeScript can do type inference. For example:
let skill = skills[0];
console.log(typeof(skill));
Output:
string
In this example, we extract the first element of the skills array and assign it to the skill
variable.
TypeScript if
An if statement executes a statement based on a condition. If the condition is truthy, the if
statement will execute the statements inside its body:
if(condition) {
// if-statement
}
For example, the following statement illustrates how to use the if statement to increase the
counter variable if its value is less than the value of the max constant:
const max = 100;
let counter = 0;
if (counter < max) {
counter++;
}
console.log(counter); // 1
Output:
1
JB PORTALS 42
FULL STACK DEVELOPMENT - WEEK 4
Ternary operator ?:
In practice, if you have a simple condition, you can use the ternary operator ?: rather than
the if...else statement to make code shorter like this:
const max = 100;
let counter = 100;
counter < max ? counter++ : counter = 1;
console.log(counter);
JB PORTALS 43
FULL STACK DEVELOPMENT - WEEK 4
The break statement that associates with each case clause ensures that the control
breaks out of the switch...case statement once the statements in the case clause complete. If
the matching case clause doesn’t have the break statement, the program execution continues
at the next statement in the switch...case statement.
TypeScript for
The following shows the syntax of the TypeScript for loop statement:
for(initialization; condition; expression) {
// statement
}
The for loop statement creates a loop. It consists of three optional expressions separated by
semicolons (;) and enclosed in parentheses:
initialization: is an expression evaluated once before the loop begins. Typically, you use the
initialization to initialize a loop counter.
JB PORTALS 44
FULL STACK DEVELOPMENT - WEEK 4
condition – is an expression that is evaluated at the end of each loop iteration. If the condition
is true, the statements in the loop body execute.
expression – is an expression that is evaluated before the condition is evaluated at the end
of each loop iteration. Generally, you use the expression to update the loop counter.
All three expressions in the for loop statement are optional. It means that you can use the for
loop statement like this:
for(;;) {
// do something
}
In practice, you should use a for loop if you know how many times the loop should
run. If you want to stop the loop based on a condition other than the number of times the
loop executes, you should use a while loop.
Examples
Let’s take some examples of using the TypeScript for loop statement.
1) Simple TypeScript for example : The following example uses the for loop statement to
output 10 numbers from 0 to 9 to the console:
for (let i = 0; i < 10; i++) {
console.log(i);
}
Output:
0
1
2
3
4
5
6
7
8
9
How it works:
declare a variable i and initialize it to 0. Then check if i is less than 10. If it is, output i to the
console and increment i by one. Finally, repeat the second step until i equals 10.
JB PORTALS 45
FULL STACK DEVELOPMENT - WEEK 4
TypeScript while
The while statement allows you to create a loop that executes a block of code as long as a
condition is true. The following shows the syntax of the TypeScript while statement:
while(condition) {
// do something
}
The while statement evaluates the condition before each loop iteration. If the
condition evaluates to true, the while statement executes the code its in body surrounded by
the curly braces ({}).
When the condition evaluates to false, the execution continues with the statement
after the while statement. Since the while statement evaluates the condition before its body
is executed, a while loop is also called a pretest loop.
To break the loop immaturely based on another condition, you use the if and break
statements:
while(condition) {
// do something
// ...
if(anotherCondition)
break;
}
If you want to run a loop a number of times, you should use the TypeScript for statement.
The following example uses the while statement to output a number to the console as long
as it is less than 5:
let counter = 0;
while (counter < 5) {
console.log(counter);
counter++;
}
Output:
0
1
2
3
4
How it works:
First, declare a counter variable and initialize it to zero. Then, check if the counter is less than
5 before entering the loop. If it is, output the counter to the console and increments it by one.
Finally, repeat the above step as long as counter is less than 5.
JB PORTALS 46
FULL STACK DEVELOPMENT - WEEK 4
TypeScript do while
The following shows the syntax of the do...while statement:
do {
// do something
} while(condition);
The do...while statement executes statements in its body surrounded by the curly
braces ({}) until the condition is false. The do...while statement always executes its loop body
at least one. Unlike the while statement, the do...while statement evaluates the condition
after each loop iteration, therefore, it is called a post-test loop.
The following example uses the do...while statement to output numbers from 0 to 9 to the
console:
let i = 0;
do {
console.log(i);
i++
} while (i < 10);
JB PORTALS 47
FULL STACK DEVELOPMENT - WEEK 4
Output:
0
1
2
3
4
5
6
7
8
9
How it works:
First, declare a variable i and initialize it to zero before entering the loop. Then, output i to
the console, increment it by one, and check if it is less than 10. If it is, repeat the loop until i
greater than or equal 10.
TypeScript break
Using TypeScript break to terminate a loop. The break statement allows you to terminate a
loop and pass the program control over the next statement after the loop. You can use the
break statement inside the for, while, and do...while statement. The following example shows
how to use the break statement inside a for loop:
let products = [
{ name: 'phone', price: 700 },
{ name: 'tablet', price: 900 },
{ name: 'laptop', price: 1200 }
];
JB PORTALS 48
FULL STACK DEVELOPMENT - WEEK 4
TypeScript Functions
TypeScript functions are the building blocks of readable, maintainable, and reusable code.
Like JavaScript, you use the function keyword to declare a function in TypeScript:
function name(parameter: type, parameter:type,...): returnType {
// do something
}
Unlike JavaScript, TypeScript allows you to use type annotations in parameters and return
value of a function. Let’s see the following add() function example:
function add(a: number, b: number): number {
return a + b;
}
In this example, the add() function accepts two parameters with the number type. When you
call the add() function, the TypeScript compiler will check each argument passed to the
function to ensure that they are numbers.
The following example shows how to declare a variable which has a function type that
accepts two numbers and returns a number:
let add: (x: number, y: number) => number;
In this example:
The function type accepts two arguments: x and y with the type number. The type of the
return value is number that follows the fat arrow (=>) appeared between parameters and
return type.
Once annotating a variable with a function type, you can assign the function with the
same type to the variable. TypeScript compiler will match the number of parameters with
their types and the return type. The following example shows how to assign a function to the
add variable:
add = function (x: number, y: number) {
return x + y;
};
Also, you can declare a variable and assign a function to a variable like this:
let add: (a: number, b: number) => number =
function (x: number, y: number) {
return x + y;
};
JB PORTALS 49
FULL STACK DEVELOPMENT - WEEK 4
If you assign other functions whose type doesn’t match to the add variable, TypeScript will
issue an error:
add = function (x: string, y: string): number {
return x.concat(y).length;
};
In this example, we reassigned a function, whose type doesn’t match, to the add function
variable.
The number of arguments is different from the number of parameters specified in the
function.
Or the types of arguments are not compatible with the types of function parameters.
Because the compiler thoroughly checks the passing arguments, you need to annotate
optional parameters to instruct the compiler not to issue an error when you omit the
arguments. To make a function parameter optional, you use the ? after the parameter name.
For example:
function multiply(a: number, b: number, c?: number): number {
if (typeof c !== 'undefined') {
return a * b * c;
}
return a * b;
}
How it works:
First, use the ? after the c parameter. Second, check if the argument is passed to the
function by using the expression typeof c !== 'undefined'.
The optional parameters must appear after the required parameters in the parameter list.
JB PORTALS 50
FULL STACK DEVELOPMENT - WEEK 4
In this syntax, if you don’t pass arguments or pass the undefined into the function
when calling it, the function will take the default initialized values for the omitted
parameters. For example:
function applyDiscount(price, discount = 0.05) {
return price * (1 - discount);
}
console.log(applyDiscount(100)); // 95
In this example, the applyDiscount() function has the discount parameter as a default
parameter. When you don’t pass the discount argument into the applyDiscount() function,
the function uses a default value which is 0.05.
A function has only one rest parameter. The rest parameter appears last in the
parameter list. The type of the rest parameter is an array type. To declare a rest parameter,
you prefix the parameter name with three dots and use the array type as the type annotation:
function fn(...rest: type[]) {
//...
}
The following example shows how to use the rest parameter:
function getTotal(...numbers: number[]): number {
let total = 0;
numbers.forEach((num) => total += num);
return total;
}
In this example, the getTotal() calculates the total of numbers passed into it. Since the
numbers parameter is a rest parameter, you can pass one or more numbers to calculate the
total:
console.log(getTotal()); // 0
console.log(getTotal(10, 20)); // 30
console.log(getTotal(10, 20, 30)); // 60
JB PORTALS 51
FULL STACK DEVELOPMENT - WEEK 4
However, the union type doesn’t express the relationship between the parameter types and
results accurately.
The add() function tells the compiler that it will accept either numbers or strings and return
a number or string. It fails to describe that the function returns a number when the
parameters are numbers and return a string if the parameters are strings.
To better describe the relationships between the types used by a function, TypeScript
supports function overloadings. For example:
JB PORTALS 52
FULL STACK DEVELOPMENT - WEEK 4
Third, create a new TypeScript file called app.ts. The extension of a TypeScript file is .ts.
Sixth, type the following command on the Terminal to compile the app.ts file:
tsc app.ts
If everything is fine, you’ll see a new file called app.js is generated by the TypeScript
compiler:
JB PORTALS 53
FULL STACK DEVELOPMENT - WEEK 4
To run the app.js file in node.js, you use the following command:
node app.js
If you installed the ts-node module mentioned in the setting up TypeScript development
environment, you can use just one command to compile the TypeScript file and execute the
output file in one shot:
ts-node app.ts
First, create a new file called index.html and include the app.js as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TypeScript: Hello, World!</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>
JB PORTALS 54
FULL STACK DEVELOPMENT - WEEK 4
Fourth, open the Live Server from the VS code by right-mouse click the index.html and select
the Open with Live Server option:
The Live Server will open the index.html with the following message:
To make the changes, you need to edit the app.ts file. For example:
let message: string = 'Hello, TypeScript!';
let heading = document.createElement('h1');
heading.textContent = message;
document.body.appendChild(heading);
The TypeScript compiler will generate a new app.js file, and the Live Server will
automatically reload it on the web browser. Note that the app.js is the output file of the app.ts
file, therefore, you should never directly change the code in this file, or you’ll lose the changes
once you recompile the app.ts file.
JB PORTALS 55
FULL STACK DEVELOPMENT - WEEK 4
Modern UI Tecgnologies
When selecting UI front-end technology, there are a number of key criteria to keep in
mind, including performance, complexity, ease of use, compatibility with both standard and
emerging technologies, and, of course, functionality and the ability to handle and solve
problems. For UI developers, selecting the right front-end UI technology for application
development can be challenging, particularly when you consider the needs and perspectives
of both users and development teams.
For example, while some technology may provide excellent features for the end user,
development teams may have limited skills when it comes to actually implementing those
features. Others may provide a high degree of flexibility for future enhancements but fall
short when it comes to features on the front end. Additionally, while most UI tech stacks
provide developer tools and support unit testing, few will have backward compatibility as
well, which is when newer versions support features from older versions.
On the other hand, there are some limitations with the technology. For example,
performance can be slower for smaller projects and, in general, the functionality and
management can be relatively complex. If there are deviations from the standard
architecture, scalability can quickly become an issue. Additionally, there’s a relatively steep
learning curve for developers and a lengthy list of style guides and best practices.
JB PORTALS 56
FULL STACK DEVELOPMENT - WEEK 4
But one of the biggest advantages of React JS Library is that it can be used in
conjunction with Angular. It’s also very easy to learn, and because it’s based on JavaScript
technology, developers who have worked with legacy technologies will be very comfortable
with tool.
While React JS Library is simple to use for small to medium-size projects, for
enterprise-level projects, developers need to be careful to get the architecture right to avoid
performance issues. Other potential drawbacks of the tool include difficulties with one-way
binding, lack of support for typescript, and challenges integrating with model view controller
frameworks.
Vue.JS: The up-and-comer
Despite its newness – and perhaps because of it – Vue.Js has already been generating
a lot of buzz in the developer community for its next-level functionality that draws on the
best features of other technologies. It takes a true developer-based approach that makes it
very easy to use, with a small learning curve.
While many developers and teams are anxious to take advantage of its next-gen
functionality, they’ll unfortunately have to wait a bit longer before leveraging it at any degree
of scale within their organization. The concepts are still in its initial phases of development
and is limited in scope. That being said, UI developers can and should begin exploring the
functionality of the framework with smaller proof-of-concept style projects.
The bottom line
While there are a range of technologies in the market, these three are key ones for UI
developers to be aware of. There’s no one technology that will work perfectly for one
organization or project, and the functionality of each technology will continue to evolve.
Development teams need to assess the pros and cons of each taking into consideration their
objectives. While Angular will continue to be the enterprise-grade powerhouse,
development teams can – and should – leverage and experiment with other
frameworks/libraries.
JB PORTALS 57