Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

FULL STACK DEVELOPMENT - WEEK 4

HTML, CSS, JavaScript Fundamentals

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.

A Simple HTML Document


<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>

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

What is an HTML Element?


An HTML element is defined by a start tag, some content, and an end tag:
<tagname> Content goes here... </tagname>

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:

HTML Page Structure

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

Why Use CSS?


CSS is used to define styles for your web pages, including the design, layout and
variations in display for different devices and screen sizes.

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;
}

CSS Solved a Big Problem


HTML was NEVER intended to contain tags for formatting a web page. HTML was created to
describe the content of a web page, like:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>

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.

The CSS element Selector


The element selector selects HTML elements based on the element name.
Example
Here, all <p> elements on the page will be center-aligned, with a red text color:
p{
text-align: center;
color: red;
}

The CSS id Selector


The id selector uses the id attribute of an HTML element to select a specific element. The id
of an element is unique within a page, so the id selector is used to select one unique element!
To select an element with a specific id, write a hash (#) character, followed by the id of the
element.
Example
The CSS rule below will be applied to the HTML element with id="para1":
#para1 {
text-align: center;
color: red;
}

JB PORTALS 4
FULL STACK DEVELOPMENT - WEEK 4

The CSS class Selector


The class selector selects HTML elements with a specific class attribute. To select
elements with a specific class, write a period (.) character, followed by the class name.

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>

The CSS Universal Selector


The universal selector (*) selects all HTML elements on the page.
Example
The CSS rule below will affect every HTML element on the page:
*{
text-align: center;
color: blue;
}

The CSS Grouping Selector


The grouping selector selects all the HTML elements with the same style definitions.
In this example we have grouped the selectors:
h1, h2, p {
text-align: center;
color: red;
}

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.

Some commonly used keywords are:


o break: This is used to terminate a loop or switch.
o continue: This is used to skip a particular iteration in a loop and move to next iteration.
o do…. while: In this the statements written within do block are executed till the condition in
while is true.
o for: It helps in executing a block of statements till the condition is true.
o function: This keyword is used to declare a function.
o return: This keyword is used to exit a function.
o switch: This helps in executing a block of codes depending on different cases.
o var: This keyword is used to declare a variable with a global scope.
o let: This keyword is used to declare a variable with block scope. Variables declared using let
need not be initialized.
o const: This keyword is used to declare a variable with block scope. Variables declared using
const must be initialized at the place of declaration.

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

JavaScript Multi line Comment


It can be used to add single as well as multi line comments. So, it is more convenient.
It is represented by forward slash with asterisk then asterisk with forward slash. For
example:
/* your code here */
It can be used before, after and middle of the statement.
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>

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

3. Javascript Data Types


Different types of values and data can be stored in JavaScript variables. To assign values to
JavaScript variables, you use the equals to "=" sign operator. The various data types in
JavaScript are as follows:
• Numbers: These are just numerical values. They can be real numbers or integers. An
example of the numbers data type is shown below: var id = 100

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.

• Comparison Operators: A list of all the Comparison operators in JavaScript is as follows:


o ==: The equality operator (==) returns a Boolean value when its two operands are equal. It
tries to convert and compare operands of different kinds, unlike the rigorous equivalent
operator.
o ===: The equivalent operator (===) returns a Boolean value when its two operands are equal
and they have the same type.
o !=: The inequality operator (!=) returns a Boolean value if the two operands are not equal.
o !==: The inequivalent operator (!=) returns a Boolean value if the two operands are not equal
or they are not of the same type.
o ?: The conditional (ternary) operator is the only one in JavaScript that takes three operands:
a condition followed by a question mark (? ), an expression to execute if the condition is true
followed by a colon (:), and lastly an expression to execute if the condition is false. As an
alternative to an if...else statement, this operator is commonly used.>: The Greater than
operator returns true if the operand to its left is greater in value than the operand to its right.
o <: The Lesser than operator returns true if the operand to its left is lesser in value than the
operand to its right.
o >=: The Greater than equals to operator returns true if the operand to its left is greater in
value or equal in value than the operand to its right.
o <=: The Lesser than equals to operator returns true if the operand to its left is lesser in value
or equal in value than the operand to its right.

• Logical Operators: A list of all the Logical operators in JavaScript is as follows:


o &&: If and only if all of the operands are true, the logical AND operator (logical conjunction)
for a set of Boolean operands is true. It will be false if it is not. When evaluating from left to
right, the operator returns the value of the first false operand encountered, or the value of
the last operand if all operands are truth.

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.

How to install Visual Studio Code on Windows OS


About VS Code
Visual Studio Code is a free source-code editor made by Microsoft for Linux, Windows, and
mac OS. VS Code has support for debugging, syntax highlighting, intelligent code completion,
snippets, code refactoring, and embedded Git. Users can change the theme, add keyboard
shortcuts, edit preferences, and install extensions to add functionality.
• Developed by: Microsoft Corporation Developer(s): Microsoft Written in: TypeScript,
JavaScript, CSS Platforms: x86-32 (32 bit Intel x86), x86-64, AArch64

How to install Visual Studio code


Step 1 : Download VS code from here Link.

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

• Accept the agreement and click “next.”

• After accepting all the requests press finish button. By default, VS Code installs under:
"C:\users{username}\AppData\Local\Programs\Microsoft VS Code."

• If the installation is successful, you will see the following:

JB PORTALS 13
FULL STACK DEVELOPMENT - WEEK 4

Install Visual Studio Code extensions


Browse for extensions
You can browse and install extensions from within VS Code. Bring up the Extensions view by
clicking on the Extensions icon in the Activity Bar on the side of VS Code or the View:
Extensions command (Ctrl+Shift+X).

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.

Find and install an extension


For example, let's install the popular TODO Highlight extension. This extension highlights
text like 'TODO:' and 'FIXME:' in your source code so you can quickly find undone sections.

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

Extensions view filter and commands


You can filter the Extensions view with the Filter Extensions context menu.

There are filters to show:


• The list of currently installed extensions
• The list of outdated extensions that can be updated
• The list of currently enabled/disabled extensions
• The list of recommended extensions based on your workspace
• The list of globally popular extensions

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

Search for an extension


You can clear the Search box at the top of the Extensions view and type in the name
of the extension, tool, or programming language you're looking for. For example, typing
'python' will bring up a list of Python language extensions:

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 ().

• In a method, ‘this’ refers to the owner object.


• Additional information can also be added along with the object method.
Syntax:
objectName.methodName()

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.

Example 1: This example use function definition as property value.


<!DOCTYPE html>
<html>
<head>
<title>
JavaScript Object Methods
</title>
</head>

<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) {

// "this" refers to the address


// of the keys "g" and "f"

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.

Adding a property to Constructor: We cannot add a property to an existing constructor


like adding a property to an object (see previous point), for adding a property we need to
declare under the constructor.
function GFG(a, b, c) {
this.A = a;
this.B = b;
this.C = c;
this.G = "GEEK";
}
Here, we add a property name G with value “GEEK”, in this case the value “GEEK” is not
passed as an argument.

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.

By default, the [[Configurable]] , [[Enumerable]]And [[Writable]] attributes set to


true for all properties defined directly on an object. The default value of the[[Value]]
attribute is undefined.

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

To change any attribute of a property, you use the Object.defineProperty() method.


The Object.defineProperty() method accepts three arguments:
• An object.
• A property name of the object.
• A property descriptor object that has four properties: configurable, enumerable, writable,
and value.

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

2) Object Accessor Properties

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.

In the fullname accessor property:


• The [[Get]] returns the full name that is the result of concatenating of firstName, space,
and lastName.
• The [[Set]] method splits the argument by the space and assigns the firstName and
lastName properties the corresponding parts of the name.

• If the full name is not in the correct format i.e., first name, space, and last name, it will
throw an error.

Why Using Getters and Setters?


• It gives simpler syntax
• It allows equal syntax for properties and methods
• It can secure better data quality
• It is useful for doing things behind-the-scenes

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>

Prototypes and inheritance


Prototypes are a powerful and very flexible feature of JavaScript, making it possible
to reuse code and combine objects. In particular they support a version of inheritance.
Inheritance is a feature of object-oriented programming languages that lets programmers
express the idea that some objects in a system are more specialized versions of other objects.

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.

REFERENCE LINK: https://www.w3schools.com/js/js_object_prototypes.asp

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.

Javascript: A general purpose scripting language that conforms to the ECMAScript


specification.It is basically an implementation which tells us how to use 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.

Book title is : Perl


Book author is : Tom
Book price is : 100

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

const numbersCombined = [...numbersOne, ...numbersTwo];


document.write(numbersCombined);
</script>

</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
:

We can use the spread operator with objects too:


<!DOCTYPE html>
<html>
<body>
<script>
const myVehicle = {
brand: 'Ford',
model: 'Mustang',
color: 'red'
}
const updateMyVehicle = {
type: 'car',
year: 2021,
color: 'yellow'

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 −

Sr.No Object Map

Keys cannot be Object type Keys can be any type


1

Keys are not ordered Keys are ordered


2

not iterable iterable


3

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

let empJobs = new Map([


[andy,'Software Architect'],
[varun,'Developer']]
);
console.log(empJobs)
</script>

The output of the above code is as shown below −

{{…} => "Software Architect", {…} => "Developer"}

Map.prototype.size: It returns the number of elements in the Map object.

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

REFERENCE LINK: https://www.geeksforgeeks.org/sets-in-javascript/


https://www.tutorialspoint.com/es6/es6_maps_and_sets.htm

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

The following methods can be used to manipulate a set −


Sr.No Object & Map

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).

As TypeScript code is converted to JavaScript code it makes it easier to integrate into


JavaScript projects. It is designed mainly for large Scale projects.
TypeScript ===>>> JavaScript + Type + Some Added Features

What does TypeScript offer ?


1. Static Type Checking (Optional) – Like other high level programming languages like Java, C
etc. TypeScript does provide static type checking unlike JavaScript. Although static typing
requires some extra steps while writing code but it has its own advantages. With TypeScript,
we can check and assign variables, parameters and function types. It is completely Optional
and helps us find and prevent bugs. Also helps make code more readable and descriptive.

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).

Why do we use TypeScript ?


1. Better developer experience – One of the biggest advantages of TypeScript is to enable
IDEs to provide a richer environment for spotting common errors as you type the code. For
a large scale project adopting TypeScript might result in more robust software, while still
being deployable where a regular JavaScript application would run.

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/

Two main reasons to use TypeScript:


1. TypeScript adds a type system to help you avoid many problems with dynamic types in
JavaScript.
2. TypeScript implements the future features of JavaScript a.k.a ES Next so that you can use
them today.

Setting up development environment for TypeScript


The following tools you need to setup to start with TypeScript:
• Node.js – Node.js is the environment on which you will run the TypeScript compiler. Note
that you don’t need to know node.js.
• TypeScript compiler – a Node.js module that compiles TypeScript into JavaScript. If you use
JavaScript for node.js, you can install the ts-node module. It is a TypeScript execution and
REPL for node.js
• Visual Studio Code or VS code – is a code editor that supports TypeScript. VS Code is highly
recommended. However, you can use your favorite editor.

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

Install TypeScript compiler


To install the TypeScript compiler, you launch the Terminal on macOS or Linux and
Command Prompt on Windows and type the following command:
npm install -g typescript
After the installation, you can type the following command to check the current version of
the TypeScript compiler:
tsc --v
It should return the verison like this:
Version 4.0.2
Note that your version are probably newer than this version.

If you’re on Windows and got the following error:


'tsc' is not recognized as an internal or external command, operable program
or batch file.

… then you should add the following path C:\Users\<user>\AppData\Roaming\npm to the


PATH variable. Notice that you should change the <user> to your windows user.

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

To install the Live Server extension, you follow these steps:

• Click the Extensions tab to find the extensions for VS Code.


• Type the live server to search for it.
• Click the install button to install the extension.

Example for first program in TypeScript:

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.

Generated JavaScript Code in types.js File:


var myString;
myString = 'Hello from ts';
console.log(myString);

JB PORTALS 38
FULL STACK DEVELOPMENT - WEEK 4

TypeScript Basic Types


REFERENCE LINK: https://www.typescripttutorial.net/typescript-tutorial/typescript-
types/

In TypeScript, a type is a convenient way to refer to the different properties and


functions that a value has. A value is anything that you can assign to a variable e.g., a number,
a string, an array, an object, and a function.

Purposes of types in TypeScript


There are two main purposes of types in TypeScript:
• First, types are used by the TypeScript compiler to analyze your code for errors
• Second, types allow you to understand what values are associated with variables.

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

string represents text data

number represents numeric values

boolean has true and false values

null has one value: null

undefined has one value: undefined. It is a default value of an uninitialized variable

symbol represents a unique constant value

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.

The number type


The following shows how to declare a variable that holds a floating-point value:
let price: number;
Or you can initialize the price variable to a number:
let price = 9.95;
As in JavaScript, TypeScript supports the number literals for decimal, hexadecimal, binary,
and octal literals:

Decimal numbers : The following shows some decimal numbers:


let counter: number = 0;
let x: number = 100,
y: number = 200;

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.

TypeScript Array Type


A TypeScript array is an ordered list of data. To declare an array that holds values of a specific
type, use the following syntax:
let arrayName: type[];
For example, the following declares an array of strings:
let skills: string[];
And you can add one or more strings to the array:
skills[0] = "Problem Solving";
skills[1] = "Programming";
or use the push() method:
skills.push('Software Design');
The following declares a variable and assigns an array of strings to it:
let skills = ['Problem Sovling','Software Design','Programming'];
In this example, TypeScript infers the skills array as an array of strings. It is equivalent to the
following:
let skills: string[];
skills = ['Problem Sovling','Software Design','Programming'];
Once you define an array of a specific type, TypeScript will prevent you from adding
incompatible values to the array.

JB PORTALS 41
FULL STACK DEVELOPMENT - WEEK 4

The following will cause an error:


skills.push(100);
… because we’re trying to add a number to the string array.
Error:
Argument of type 'number' is not assignable to parameter of type 'string'.

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.

Control Flow Statements

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

TypeScript if…else statement


If you want to execute other statements when the condition in the if statement evaluates to
false, you can use the if...else statement:
if(condition) {
// if-statements
} else {
// else statements;
}

JB PORTALS 42
FULL STACK DEVELOPMENT - WEEK 4

The following illustrates an example of using the if..else statement:


const max = 100;
let counter = 100;
if (counter < max) {
counter++;
} else {
counter = 1;
}
console.log(counter);
Output:
1
In this example, the expression counter < max evaluates to false therefore the statement in
the else branch executes that resets the counter variable to 1.

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);

TypeScript if…else if…else statement


When you want to execute code based on multiple conditions, you can use the if...else if...else
statement. The if…else if…else statement can have one or more else if branches but only one
else branch. For example:
let discount: number;
let itemCount = 11;
if (itemCount > 0 && itemCount <= 5) {
discount = 5; // 5% discount
} else if (itemCount > 5 && itemCount <= 10) {
discount = 10; // 10% discount
} else {
discount = 15; // 15%
}
console.log(`You got ${discount}% discount. `)
Output:
0

JB PORTALS 43
FULL STACK DEVELOPMENT - WEEK 4

TypeScript switch case :


The following shows the syntax of the switch...case statement:
switch ( expression ) {
case value1:
// statement 1
break;
case value2:
// statement 2
break;
case valueN:
// statement N
break;
default:
//
break;
}
How it works:
First, the switch...case statement evaluates the expression. Then, it searches for the
first case clause whose expression evaluates to the same value as the value (value1, value2,
…valueN).
The switch...case statement will execute the statement in the first case clause whose
value matches. If no matching case clause is found, the switch...case statement looks for the
optional default clause. If the default clause is available, it executes the statement in the
default clause.

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 while practical example


Let’s say you have the following list element on an HTML document:
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
The following example shows how to use the while statement to remove all <li> element of
the <ul> element:
let list = document.querySelector('#list');
while (list.firstChild) {
list.removeChild(list.firstChild);
}
How it works:
First, select the <ul> element by its id using the querySelector() method. Then, check
if firstChild of the list is available and remove it. Once the first child node is removed, the
next child node is automatically promoted as the first child node. Therefore, the while
statement removes all child nodes of the list element.

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 }
];

for (var i = 0; i < products.length; i++) {


if (products[i].price == 900)
break;
}

// show the products


console.log(products[i]);
Output:
{ name: 'tablet', price: 900 }
How it works:
First, initialize a list of products with name and price properties. Then, search for the
product whose price is 900 and terminate the loop once the product is found by using the
break statement. Finally, show the matching product to the console.

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.

TypeScript Function Types


A function type has two parts: parameters and return type. When declaring a function
type, you need to specify both parts with the following syntax:
(parameter: type, parameter:type,...) => type

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.

TypeScript Optional Parameters


In JavaScript, you can call a function without passing any arguments even though the
function specifies parameters. Therefore, JaveScript supports the optional parameters by
default. In TypeScript, the compiler checks every function call and issues an error in the
following cases:

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.

TypeScript Default Parameters


JavaScript supported default parameters since ES2015 (or ES6) with the following syntax:
function name(parameter1=defaultValue1,...) {
// do something
}

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.

TypeScript Rest Parameters


A rest parameter allows you a function to accept zero or more arguments of the
specified type. In TypeScript, rest parameters follow these rules:

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

TypeScript Function Overloadings


In TypeScript, function overloadings allow you to establish the relationship between
the parameter types and result types of a function.
Note that TypeScript function overloadings are different from the function overloadings
supported by other statically-typed languages such as C# and Java.

JB PORTALS 51
FULL STACK DEVELOPMENT - WEEK 4

Let’s start with some simple functions:


function addNumbers(a: number, b: number): number {
return a + b;
}
function addStrings(a: string, b: string): string {
return a + b;
}
In this example:
The addNumbers() function returns the sum of two numbers.
The addStrings() function returns the concatenation of two strings.
It’s possible to use a union type to define a range of types for function parameters and results:
function add(a: number | string, b: number | string): number | string {
if (typeof a === 'number' && typeof b === 'number')
return a + b;
if (typeof a === 'string' && typeof b === 'string')
return a + b;
}

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:

function add(a: number, b: number): number;


function add(a: string, b: string): string;
function add(a: any, b: any): any {
return a + b;
}
In this example, we added two overloads to the add() function. The first overload tells
the compiler that when the arguments are numbers, the add() function should return a
number. The second overload does the same but for a string.

Each function overload defines a combination of types supported by the add()


function. It describes the mapping between the parameters and the result they return.

JB PORTALS 52
FULL STACK DEVELOPMENT - WEEK 4

TypeScript “Hello, World!”


TypeScript Hello World program in node.js

First, create a new folder to store the code, e.g., helloworld.

Second, launch VS Code and open that folder.

Third, create a new TypeScript file called app.ts. The extension of a TypeScript file is .ts.

Fourth, type the following source code in the app.ts file:


let message: string = 'Hello, World!';
console.log(message);
Fifth, launch a new Terminal within the VS Code by using the keyboard shortcut Ctrl+` or
follow the menu Terminal > New Terminal

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

TypeScript Hello World program in Web Browsers


You follow these steps to create a webpage that shows the Hello, World! message on web
browsers.

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>

Second, change the app.ts code to the following:


let message: string = 'Hello, World!';
// create a new heading 1 element
let heading = document.createElement('h1');
heading.textContent = message;
// add the heading the document
document.body.appendChild(heading);

Third, compile the app.ts file:


tsc app.ts

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);

And compile the app.ts file:


tsc app.ts

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.

Choosing the right technology for your application


Angular, React JS Library, and Vue.js are three key technologies that are on the radar
of UI developers, and each has its own set of advantages and disadvantages. Here, we break
down each one as well as its potential advantages and drawbacks for creating fast, secure,
and next-gen UI applications.

Angular Frameworks: The enterprise-grade powerhouse


Angular Frameworks is an application design framework and development platform
for creating efficient and sophisticated single-page web apps. It’s the technology that is
currently used for most large, enterprise-level projects. For many companies, it is the de-
facto UI technology, and because of that, it has number of advantages. For example, it
provides unparalleled modularity, which makes work in large teams easier. Each team
member can work on their part of the code without being afraid to break anything in
someone else’s code. It also enables easy unit testing to simplify and accelerate the process
of finding errors and defect and offers two-way data-binding and custom directives.
Additionally, the deployment generally goes more smoothly than in other technologies given
its powerful CLI.

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

React JS Library: When high speed and volumes are required


React JS Library is an open source JavaScript library designed to help developers
create rich and engaging web apps quickly and efficiently with minimal coding. It tends to be
used for small to medium projects as well as for high-performance applications that require
speed, efficiency, and the ability to handle large volumes. One of its best features is server-
side rendering, which makes it a great technology to use for high-traffic websites.
Additionally, its “react native” functionality allows teams to quickly develop efficient
Android or IOS mobile apps without needing to learn android or IOS programming.

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

You might also like