You are on page 1of 66

=what is web application ?

is application which can be accessed from anywhere and provides services over the
internet.
For ex gmail.com,facebook.com,amzon, irctc.

1.static web application


data and info doesn't change with respect to person to person or time to time.

2.dynamic web application


an application whose data and info is changes with respect person to person or
time to time.
For ex.facebook.com , amazon ,gmail

to develop an dynamic web application we need to follow some structure/architecture

3-tier architecture need to follow to


1.Client
2.Server
3.DataBase

to devlop an any dynamic web application two things are rwquired


1.FrontEnd
to develop an front end we need html,css,Bootstrap,Javascript/typescript

1.HTML -> it represents the structure of data

2.CSS -> Cascading style sheets


css is used to apply style to an web components.

3.Javascript/TypeScript ->
to perform an action on any webpage we need to use JavaScript.
to add functionality to any html elemnts then we need to use.

Bootstrap,JQuery.
Bootstrap => provide readymade classes to apply css instead of applying manually
CSS.

Angular,ReactJS

Static Data :
the data which is not changed from person to person or time to time then it is
called static data.
HTMl and CSS is sufficient to develop.

Dynamic Data :
will be changed from person to person or time to time .
for dynamic data html is not sufficient we need Javascript.

2.Backend
is respnsible to save data which is generated from our application
for ex.signUp Page
also it is responsible to which things we need to show on web page.

FrontEnd technologies(HTMl,CSS,JS/Ts) doesn't have capbility to connect with


database.
hence we need server side technologies
for ex. java,nodeJs,python,dot net

==============
What is Angular ?
angular is client-side-framework used to develop dynamic web application.

angular framework is developed by =>google.

the main use of angular is to develop single page application.


what is single page application means ?
data /content is loaded dynamically
page reload is not required while using the application.
application will be fast.
For ex.gmail.com,Facebook.com,Github

multi-page application.

angular JS and angular 2


angular Js framework was developed using JavaScript
Angular is developed using TypeScript.

angular JS and Angular are both different frameworks.

typescript =>
it is an open source programming langugae.
developed by => microsoft

framework => is nothing but an ready made modules or pre defined modules,readymade
classes and readymade function.
using framework we can make development easy,fast.

typescript => typescript is superset of javascript


tyepscritpt = js + types+oop features.

ts is develoed by using JS as base language.

typescript vs javascript =>

1)
javascript is dynamically typed language
typescript is strongly typed language

for ex
Incase Of JavaScript
var x = 10 ;
x = "Hi";
x = false ;
console.log(x); o/p false ;

incase Of TypeScript
var x = 10 ;
x = "Hello";
console.log(x); throw an error due to strictly typed language.
var x:number = 10 ;
x = "Hi"
console.log(x); // throw an error due to strictly typed language.

2.
Javascript is not strictly types language
Typescript is strictly typed language

2.
function arguments and parameters are not mandatory incase of JS.

function add(x,y){
console.log(x+y);
}

add(5,6); //o/p 11

add(5); // NAN
add(); // it will run doesn't give an error

function areguments and parameters are mandatory incase of TS.

function add(x,y){
console.log(x+y);
}

add(5,6); //o/p 11

add(5); // compiler time error.

or while declaring parameters we can define type of parameters incase of


TypeScript.but JS doesn't allow type.
for ex. x is of type number.
function add(x:number,y:number){
console.log(x+y);
}

add('2',3);

3.js does not support oops features


ts support oops features
for ex classes, interfaces, inheritance etc.

4.
.ts extension
.js extenion

5.
typescript will give error at compile time
javascript will give error at runtime.

a valid javascript is valid typescript code.


but a valid typescript code is not valid javascript code.

Variable and (Built in)or Primitive Data Types:


Variable:
Variable are used to store data or information.

using var,let,const we can declare variables in typescript.

for ex. syntax


var x = 10 ;
var = keyword
x = variable name or dataholder which holds the value.
10 = value

Data Type =>


helps us to what kind of value the data has.
whether it is number,string,boolean etc

data types :
1.number
2.string
3.boolean

1.number => number is data type which is used to represent numeric data.
for ex.

var price:number = 3000;


console.log(price);
var discount:number = 100;

here
var => keyword used to declare varaibles in ts
price => it an variable Name or dataholder which holds the value
number => is data type. when you specify data type number then you can store only
numeric data in variable.
3000 => value/data .

console.log() -> printing statement

2.string
It is built data type.
used to represent or store alphabets or textual data.

For Ex.

var message:string = "Good Morning";


console.log("message " + message);

3.boolean
It is built data type.
is used to represent or store boolean type of data either true or false.

for ex
var isLoggedIn : boolean = false ;

internal value of false is 0 ;


internal value of true is 1 ;

====== String Examples ===============


// find the length of string
var message:string = "Good Morning";
console.log("length is "+message.length);

//find length of string and store in number variable


var message1:string = "Good Morning";
var messagelength1:number; // declaration
messagelength1 = message1.length ; // initialization

//or
var messagelength1:number = message1.length ; //declaration and initialization
console.log(messagelength1);

//get character of string at specified index


console.log("Character is "+message[6]);

Array:
when you want store multiple data/values in single variable then we need to use an
array

without arrays
var x:number = 10 ;

with arrays
var x:number[] = [10,20,30,40,50];

By using Index we can access array elements.


Array Index starts with 0 i.e the index of first element of array is 0.

Length => no of elements present in the array we need count from 1.

//string type array


var players:string[] = ["Sachin","Virat","Rohit"];
console.log("Player List is ",players);

//number type array


var numberList:number[] = [1,2,3,4,5];
console.log(numberList);

//find the length of array


var players:string[] = ["Sachin","Virat","Rohit"];
console.log("Length of playerList " , playerList.length); // 3

//blank array
var list:string[] = [];
console.log(list.length); // 0

// find the length and store in another variable


var players:string[] = ["Sachin","Virat","Rohit"];
var count : number = players.length ;
console.log(count); // o/p 3

//find the specific element from an aray


//array index starts with 0
var playerList:string[] = ["Sachin","Virat","Rohit"];
console.log(playerList[1]); // Virat
//Note : If you are accessing an element by using out of range index then you will
get Undefined value not error.
var players:string[] = ["Sachin","Virat","Rohit"];
console.log(players[10]); // o/p undefined - at index 10 we dont have any value

any type =>


====================
it is a special data type in typescript.
it is used when you dont know the type of data then use any data type.
we can store any type values in that variable.

Ex.1
var product:any = "Mobile"; // initialization
product = 20000; // reinitialization
product = ["Mobile","Laptop","TV"]; //reinitialization
console.log(product);

Ex.2
var x : any = 20;
x = false
console.log(x); // o/p false

======
Ex.1
var x : string | number = 10;
x = "Ten";
console.log(x);

x = false // error

Ex.2

======================

08-02-2023

string + number = string;


for ex. '10' + 10 = 1010 ;
number + number = number
2+3 = 5
number+ string = string
3+'2' = 32
string+string = string
"Hello" + "Everyone" = "Hello Everyone"

Object
------
by using arrays we can store group of data/values in single variable but we cannot
store data in key-value pairs.

If we want to represent/store a group of key-value pairs data then we should go for


objects.

Ex.1
var playerObj : any = {
firstName : "Virat",
lastName : "Kohli",
age : 35
}

//access object properties using dot operator.


console.log(playerObj.lastName);

console.log(playerObj.age);

console.log("First Name :" + playerObj.firstName + "Last Name : " +


playerObj.lastName);

console.log(playerObj.firstName + " " +playerObj.lastName);

//extract age from object and store in another obj


var ageOfPlayer:number = playerObj.age;
console.log(ageOfPlayer);

var playerObj2 : any = {


firstName : "Sachin",
lastName : "Tendulkar",
age : 41
}

**nested obj (object inside another object)


-----

var personObj : any = {


firstName : "Sam",
mobileNo: 8989898989,
gender: "Male",
address : {
city : "Pune",
state: "Maharashtra",
country: "India"
}
}

console.log(personObj.address.country);

console.log(personObj.address.city);

Ex.2
var personObj : any = {
firstName : "Sam",
mobileNo: 8989898989,
gender: "Male",
address : addressObj
}

var addressObj : any = {


city : "Pune",
state: "Maharashtra",
country: "India"
}

console.log(personObj.address.country);

console.log(personObj.address.city);

// array inside object


var personObj : any = {
firstName : "Sam",
mobileNo: 8989898989,
gender: "Male",
address : {
city : "Pune",
state: "Maharashtra",
country: "India"
},
skills : ["Angular","HTML","CSS","Python"]
}

console.log(personObj.skills[0]);
console.log(personObj.skills[3]);
//
var personsSkills:string[] = personObj.skills;
console.log("Total skills : " +personsSkills.length);

==========================
09-02-2023

Ex.
var personObj:any = {};
personObj.firstName = "David";
personObj.age = 42 ;
console.log(personObj)

Object Types
interface

Using Interface we can assign type to the objects


the object type consist of key:type pairs
where
key - name of key
type - type of key for ex any data type we can assign depend upon our requirement

using interface we can put restriction on object.

When you are Initializing object of type interface then it is mandatory to define
property which are in interface
also data type should be same.

Ts compiler will throw an error when we try to access property which is not defiend
in interface
TS compiler will throw an error when you assign new property or if you assign new
data type for property.

Ex.
// use interface for type checking

interface Product {
productName:string,
price:number,
discount:number
}

var product:Product = {
productName:"Mobile",
price:20000,
discount:200
}

console.log(product);

-use ? mark to make fields nonmandatory in interface while creating object


interface Product {
productName:string,
price:number,
discount?:number
}

var product:Product = {
productName:"Mobile",
price:20000,
}

var product2:Product = {
productName:"TV",
price:30000,
discount:200
}

Array of objects
is nothing but group of objects of particular type.
for ex
we can store the set of student class objects in array of objects.

syntax
var variableName:interfcaeName[] = [obj1,obj2,obj3.....]

Ex.

interface Person {
fullName:string,
designation:string,
age:number
}

//array of objects
var employeeList:Person[] = [
{
fullName: "David",
designation: "Software developer",
age: 40,
},
{
fullName: "Mike",
designation: "Angular developer",
age: 42,
},
{
fullName: "John",
designation: "Python developer",
age: 32,
},
{
fullName: "Sam",
designation: "Java developer",
age: 30,
}
]

//print "python developer" on console


console.log(employeeList[2].designation);

//update same designation from "java developer" to "full stack developer"


employeeList[3].designation = "full stack developer";
console.log(employeeList);

//total no of employee
console.log("Total no of employees "+ employeeList.length);

Ex.2
interface Product {
productName:string,
price:number,
discount?:number
}

var productList:Product[] = [

{
productName:"Mobile",
price:20000,
},
{
productName:"TV",
price:30000,
discount:200
}

]
==============================
predefined data types provided by angular/built data types in typescript
1.number
2.string
3.boolean
4.any
5.null
6.undefined

custom data-type, user defined data types


1.interface
2.class etc

special data types


any
null
undefined

null vs undefined
are special pre-built data types in typescript.
null and undefined both acts as value as well as data type in typescript.

undefined
----------
1.if you declare an variable but doesn't assign the valut to that variable
then that variable is called undefied.

2.TS will assign undefined value to that variable


var a;
console.log(a); // undefined

or
var x:number;
console.log(x);// undefined

3.value is not initialized or we do not know its value

4.undefined is also acts as data type in typescript.


let num:undefined;
num = undefied // o/p undefined

Null in TypeScript :
----------------
1..null means nothing if you declare an variable we are assigning null value to
that variable
null means nothing absence of any value

2.ts doesn't set null value we can set null value to that variable

var x = null ;
console.log(a);
3. value is assigned but it is null means nothing

4.
null is also data type in typescript
let num:null;
console.log(num);o/p undefined

num = null ;
console.log(num)// o/p null

5.the only value that you can assign to null type variable is null or undefied.

Ex.1
var message : string | null = null;
message = "Good Morning";

console.log(message);

Ex.2
var employeeeList : string[] | null = null;
employeeeList = ['Sam','Mike'];
console.log(employeeeList);

undefined examples
------------
Ex.1
var message;
console.log(message);

Ex.2
var x;
console.log(x);

Ex.3
var message : undefined = undefined ;
console.log(message);

Ex.4
var messgae : string | undefined;

messgae = "Good Morning";


console.log(messgae);

Operators
------------------------
1.arithmetic operators
+,-,*,%,/ , ++ , --
2.comparision operators
< , <= , > , >= , == , === , != , !==

3.logical operators
&& , || , !
1.Arithmetic operators
-------------------------

% -> reminder operator


--------
100 % 20 = 0

100 / 20 = 5

Ex.
var x1:number = 100 ;
x1 = x1 + 10 ; // adding 10 in x1 variables
console.log(x1);

var x:number = 100 ;


var y:number = 50 ;

console.log(x - y);

console.log(x * y);

console.log(x % y); // 0 reminder is 0

console.log(x / y); // 2;

var x :number= 10 ; // initialization


x = x + 5 ; // reinitialization
console.log(x);

var x : number = 20 ;
var y : number = 10 ;
var result :number = x - y ;
console.log(result);

divide x by y and store the result is different variables


-----------
var result1 = (x % y);
console.log(result1);

--------------
++ , --

"++"
is used to add 1 to value.

"++" is equal to "x = x + 1"

"--"
is used to decrement the value by 1.

"--" is equal to "x = x - 1";

without increment operator


----------------
var num1 : number = 20;
num1 = num1 + 1 ;
console.log(num1); // 20

there are 2 ways we can use the "++" or "--" operator

1.pre-increment
-------
value is increment first and then it returns value

var num1:number = 20 ;
++num1

console.log(num1)

2.post-increment
-----------
var num1:number = 20 ;
num1++
console.log(num1);

Ex.1

var num1:number = 20 ;
console.log( ++num1); // value is incrment by 1 and return the value
console.log(num1);

Ex.
var num1:number = 20 ;
console.log(num1++) ; //
console.log(num1);

Ex.2
var num2:number = 10 ;
--num2;
console.log(num2);

Ex.
var num2:number = 10 ;
console.log(num2--) ;// 1
console.log(num2); //

var num2 : number = 10 ;


++num2; //11
num2--; //11
++num2 //
console.log(num2);

var num2 : number = 10 ;


num2--; //10
++num2; // 10
num2-- ; // 10
console.log(num2);
2.comparision operators
--------------------
< , <= , > , >= , ==, === , != , !==,

var num1 : number = 10 ;


var num2 : number = 11 ;

console.log(num1 > num2)

var num1 : number = 10 ;


var num2 : number = 11 ;

console.log(num1 > num2); // false


console.log(num1 >= num2); // false
console.log(num1 < num2); // true
console.log(num2 <= 11); // true

difference between = , == , ===


-----------------------
1. = operator is used to assign value to variable
for ex.
var x = 10 ;

2. == , === are equality operator.


used for comparison

difference between == && ===


== (equality operator) => value is important while comparing but not data types.

=== (Strict equality operator)=> value and data type is important while comparing.

=== operator is recommended to use.

"==" operator
value is same -> true
value is different -> false ;

"===" operator
values and data types same then -> true
value or data type is different -> false

Ex.
var num1 : number = 10 ;
var num2 : string = '10' ;
var num3 : string = 'ten';

// == && ===

console.log(num1 == num2); // true


console.log(num1 === num2); // false // value are same but data type is
different hence result is false

console.log(num2 === num3); // false // values are different

console.log(num2 == num3); // false // values are different

---------------
"!=" operator
values are different => true
values are same => false ;

"!==" operator
value or data types is different => true
value and data types is same then result => false

Ex.
var num1:number = 10 ;
var num2 : string = '10';
// != && !==
//== ===

// != -> value should be different

console.log(num1 != num2); // false values are same hence result is false

console.log(num1 !== num2); // data type is different hence result is true

===========================================================================
Logical Operators
---------------
&& , || , !

cond1 && cond2 => if both conditions are true then only o/p will be true

cond1 || cond2 => if any one condition is true then o/p will be true.

! => Logical Not operator

&& -> And


|| -> OR
! -> Not

Note:
false || true => true

true || false => true

true && true => true

true && false && false => false


Ex.
var a:number = 20 ;
var b:number = 30 ;

(a > 20) && (b < 30)

================================

var a:number = 20 ;
var b:number = 30 ;

console.log((a > 20) && (b < 30));

console.log(a >= 20 && b <= 30);

console.log(a >= 20 || b > 30);

console.log(a >= 10 && b <= 20 && b >= 30);

console.log((a >= 10 && b <= 20) || b >= 20);

"!" : Not Operator


-----------
Ex.
var a:number = 20 ;
var b:number = 30 ;

var x:number = 0 ;

console.log(!(a > 20));

console.log(!a);

console.log(!x);

Ex.
var a:number = 20 ;
var b:number = 30 ;

console.log(!(a > 10) && a == 20 && b >20)

Ex.
var message:string="";
console.log((message.length > 0) || !0);

Ex.
console.log(null == undefined); // true values are false

console.log(null === undefined); // false

Note:
1. 0 (Zero),null,undefined,""(empty string) is always considered as false.
value is false.

2.non empty string , non zero value are considered as true.

=========================================================================

statements
-------------
1.if statement
2.if-else
3.if- else if-else statement

1.if statement
------------
condition is true then statements will excute.

if(condition){
//statements

Ex.1 If age is greater than 18 show "elgible" message;

var age:number = 10 ;

if(age >= 18){


console.log("you are eligible for voting");
}

Ex.2 show eligible message when user age is greater than 18 and voterId available
var age:number = 30 ;
var isVoterCardAvailable:string = "No";

if((age >= 18) && (isVoterCardAvailable == 'Yes')){


console.log("you are eligible for voting");
}else {
console.log("You are not eligible for voting");
}

Ex.3 age is greater than 18 and "voterCard" available then show "eligible" message
age is greater than 18 and "voterCard" not available then show "create
voterId"
else "Not eligible"

var age:number = 12 ;
var isVoterCardAvailable:string = "No";

if((age >= 18) && (isVoterCardAvailable == 'Yes')){


console.log("you are eligible for voting");
}
else if((age >= 18) && (isVoterCardAvailable == 'No')){
console.log("Please creare your voter id");
}
else{
console.log("You are not eligible for voting");
}

Assignments
--------
1.Check whether the given number is positive number or not.

var x : number = -10 ;

if(x > 0){


console.log(x+" is a positive number");
}else {
console.log(x+ " is a negative number");
}

2.
If number is between 6 and 12 print "Good Morning" Message
If number is between 12 and 18 print "Good afternoon" message
else "good evening"

3.
Print the maximum number among three numbers
var num1:number = 10 ;
var num2:number = 20 ;
var num3:number = 30 ;

var num1:number = 10 ;
var num2:number = 20 ;
var num3:number = 30 ;

if(num1 > num2 && num1 > num3){


console.log("Maximum No among three number is " +num1)
}else if(num2 > num1 && num2 > num3){
console.log("Maximum No among three number is "+num2);
}else {
console.log("Maximum No among three number is "+num3)
}

4.
var userId : string = "test123";
var password:string = "welcome123";

check whether userId is "test123" and password is "welcome123" if credentials


matches
print "user id and password correct"
else "please enter the valid credentials";

==============================================================================

DRY -> dont repeat your code


Iterative Statements:
If we want to excute a group of stataments repeatedly then we need to use
iteratice stataments.

1.while loop
2.for loop

while loop:
when you want to excute block of code(group of stataments) repeatedly and
if we dont know no of iterations in advance then we should use while loop
while loop will excute as long as condition is true.

syntax:
while(condition){
// statements
}

1.Print Good Morning message 10 times on console


console.log("Good Morning");
console.log("Good Morning");
-
_
etc
but code is getting repeated hence we need to use iterative statements.

Ex.
var x:number = 1 ;
while(x <= 10){
console.log("Good Morning");
x++ ;
}

Ex.2

//print the numbers between 10 to 50 which are divisible by 5

var n1:number = 10 ;
while(n1 <= 50){
if(n1 % 5 == 0){
console.log(n1);
}
n1++ ;
}

Ex.3
//print each character of string "Good Morning" ;
var message:string = "Good Morning";

var i = 0 ;
while(i < message.length){
console.log(message[i]);
i++;
}
2.for loop
------------
when you want to excute code repeatedly and if we know the iterations in advance
then we should use for loop.
Syntax:
for(initialization,condition,increment){
//stataments
}

1.print "Welcome" message 10 times on console.

for(var i =0;i< 10 ; i++){


console.log("Welcome");
}

2.Print event number between 10 and 20

//10 to 20 even number

for(var i=10;i<=20;i = i+2){


console.log(i);
}

3.Print each character of given string.


var message:string = "Welcome";
for(var i=0;i<message.length ; i++){
console.log(message[i]);
}

---------Assignment-----------------------
1.Print odd numbers between 1 to 10 using for and while loop

2.Find sum of elments from 1 to 10 (using for loop) and while loop

3.Print 5's Table on console


Ex.
5 * 1 = 5 ;
5 * 2 = 10 ;
5 * 3 = 15 ;
etc

console.log(5 * i = )

4.Find the sum of array elements


var arr = [10,20,30,40,50]

var arr = [10,20,30,40,50]

var result = 0 ;
for(var n1=0;n1<arr.length;n1++){
result = result + arr[n1];
}
console.log(result);
console.log("Hello");

5.Print elements in reverse order from 1 to 10;


for ex.
10
9
8
...

//10 , 9 , 8 ,7 ...1
for(var i=10;i>=1;i--){
console.log(i);
}

=================================

16-02-2023

break
-----
break statement is used to break the loop.
it is used to exit from the loop when certain condition not matches.
normally when condition failed for/while loop will stop but in midway you want to
stop the for loop on certain condition then we can use break.

Ex.1
print element from 1 to 10 but break the loop when value of i is 5.

for(var i=1;i<=10;i++){
if(i == 5){
break;
}
console.log(i);
}

Ex.2 find the first even number from the given array
var num = [10,20,21,23,45]

for(var i=0;i<num.length;i++){
if(num[i] % 2 == 0){
break ;
}
}

Ex.3 find the first two even number from the given array

var num = [21,24,23,40,11]

var counter : number = 0


for(var i=0;i<num.length;i++){
if(num[i] % 2 == 0){
console.log(num[i])
counter ++
}
if(counter == 2){
break ;
}

continue
-------
continue statement will skip the iteration of the loop and continue next iteration.
hence code written after the continue statement will not excute for this particular
skipped iteration.

break statement will break the for loop and exit from the loop but continue
statement will skip the current iteration of the loop.
the similarity between break and continue is the code written after the statement
will not excute.

1.Print the elements from 1 to 10 but skip element 5


for(var i=1;i<=10;i++){
if(i == 5){
continue;
}
console.log(i);
}

Ex.2 Print even number from 1 to 10 using continue statement


for(var i=1;i<=10;i++){
if(i % 2 == 1){
continue
}
console.log(i);
}

================================================================

// var x:number = 10 ;

// if(x % 2 == 0){
// console.log(`${x} is an even number`);
// }else{
// console.log(`${x} is an odd number`);
// }

// var y:number = 20 ;
// if(x % 2 == 0){
// console.log(`${x} is an even number`);
// }else{
// console.log(`${x} is an odd number`);
// }

in above example if we see code is getting duplicated even I want to perform same
functionality.
disadvantages :
1.code is getting duplicated
2.line of code is increased
3.development time increased.

To solve the above problem we need to use functions.

If any code is repeatedly required in our application then it is not recommended to


write that code repeatedly everytime.
we need to add that lines of code in function and we need to call that function
where ever it is required.

main advantages of function is code reusability.

function can perform specific tasks and also function can caluate values.
In function we can pass input value as parameters and also function can return
values.

Ex.
function evenOrNot(x:number) {
if(x % 2 == 0) {
console.log(x + " is an even number");
} else {
console.log(x + " Is an odd number");
}
}

evenOrNot(10);
evenOrNot(21);

1.find sum of elemtns between 1 to 10 and if result is greater than 10 break the
loop;
var result = 0 ;
for(var i=1;i<=10;i++){
result=result + i ;
if(result > 10){
break ;
}
}

2.Write a function to check string is palindrome or not.


var str1 = dad ;

Soln 1:
----
var reverse : string = "";
function isPalindrome(str: string) {
for (var i = str.length - 1; i >= 0; i--) {
reverse = reverse + str[i];
}

if (str == reverse) {
console.log("Palindrome")
} else {
console.log("It is not palindrome");
}
}

isPalindrome("dad");

"radar"

"welcome"

or

Sol2
----
function isPalindrome(str:string){
for(var i = 0 ; i< (str.length/2 - 1);i++){
if(str[i] !== str[(str.length - 1)- i]){
return false ;
}
}
return true ;
}

var res = isPalindrome("radar");


if(res){
console.log("Palindrome")
}else {
console.log("Not Palindrome");
}

Sol3
----------
function isPalindrome(str:string){
for(var i = 0 ; i< (str.length/2 - 1);i++){
if(str[i] !== str[(str.length - 1)- i]){
return console.log("Is Not Palindrome") ;
}
}
return console.log("Palindrome") ;
}

isPalindrome("welcome");

3.write a function to take any number as input and find the factorial of given
number
for ex. 4
o/p => 4*3*2*1 = 2

var result = 1 ;
function isFactorial(n1:number){
for(var i=n1;i>1;i--){
result = result * i ;
}
return result ;
}

var res = isFactorial(3);


console.log(res);
4. Write a function to which will take array as input and find avarage of array
elements
For ex.
Input : [10,20,30,40,50]
O/p : 30

==================================

Function syntax:
---------
syntax :
function functionName(arguments){
body
retur value // return statament is not mandatory depend upon your requirement you
can either return or excute the functionality.
}

Ex.1
---
function hello(){
console.log("Hello Everyone");
}

hello();

Function with parameters


-----------------------
function can accept any number of arguments these are input to the function.
we can use that arguments inside the function based on our requirement.

Ex.1 wish to specific person

function hello(name:string){
console.log("Hello " + string);
}

Ex.2
Check whether given number is even or not.

function evenOrNot(x:number){
if (x % 2 == 0) {
console.log(`${x} is an even number`);
} else {
console.log(`${x} is an odd number`);
}
}

evenOrNot(20);
Ex.3
function add(x1:number,x2:number){
console.log("Addition is " + (x1+x2));
}

add1(10,20);
add1(20,30);

Ex.4
check whether number is positive or negative or zero

function isPositiveOrNegative(x: number) {


if (x > 0) {
console.log("Positive Number " + x);
} else if(x < 0){
console.log("Negative Number " + x);
}else {
console.log("Number is Zero");

}
}

isPositiveOrNegative(11);

Ex.5
---
function test(arr:number[]) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
console.log(arr[i] + " is an even number");
} else {
console.log(arr[i] + " is an odd number")
}
}
}

test([10,20,30,40]);

Function with return values


-----------------------
function can return values as well.
function can perform specific tasks and they can return from the function.
we need to take one variable to hold the result of function.

Ex.
function add(x1:number,x2:number){
return x1 + x2 ;
}

var result = add(10,20);


console.log(result);

Ex.2 write a function which will take array as n=input [10,20,30]


and find the sum of array elements.

function sum(arr:number[]){
var result : number = 0 ;
for(var i=0;i<arr.length ; i ++){
result = result + arr[i]
}

return result ;
}

var finalResult = sum([10,20,30,40,50]);


console.log(finalResult);

Ex.3

function calculateTotalprice(amount:number,discount:number){
return amount - discount;
}

var finalPrice = calculateTotalprice(10000,100);


finalPrice = finalPrice + 10;
console.log(finalPrice);

function sayHello(name:string){
console.log("Hello "+ name);
}

sayHello("Mike");

sayHello("John");

Ex.
function add(x1:number,x2:number){
console.log(x1 + x2);
}

a
dd(10,20);
add(20,30);

NAN(not a number)
-------

10 + undefined = NAN;

Assignment
---------------
Write a function take array as input and check elements are identical or not.
For ex.
Input : [1,1,2,3]
Output : false
Input: [5,5,5];
output: true

string + string = ""

Input :[10,20,30,40,50];
Output : 50 ;
==================================================
2.Anonymous functions

-sometime we can define the function without name such type of nameless function
are called Anonymous functions.
-Anonymous function has function keyword but they does not have name.
-normally this function are used for instant use(one time usage).
-this function can be passed as input to another function.
-Since anonymous function doesn't have same so to access/call/invoke anonymous
function
we need to assign anonymous function to the variable.

Syntax:
function(){
// Body of function
}

Ex.1 Anonymous Functions without parameters

/*
var hello = function(){
console.log("hello everyone");
}

hello()
*/

Ex.2. Anonymous Functions with parameters

/*
//function with parameters
var isEven = function(x:number){
if(x%2 == 0){
console.log(`${x} is Even Number`);
}else{
console.log(`${x} is odd number`);
}
}

isEven(6);

*/

Ex. 3 Anonymous Functions with return statement


/*
var sum = function(x1:number,x2:number){
return x1 + x2 ;
}

var result = sum(4,6);


console.log(result);
*/

3.Arrow functions or fat arrow functions or lambda expression


- this is special function
- introduced as part of ES6 Specification
- while declaring the Arrow function we dont require function keyword.
parameters and curly brackets are seprated with "=>" (fat arrow) that is why it
called as arrow function.
- to call or to invole the arrow function we need to assign this arrow function
to variable.
Syntax:
(param1,param2,....) => //body of function

How to create arrow function


-------
Take any anonymous function expression
for ex.
var add = function(x1,x2){
return x1 + x2 ;
}

from the above function


1.remove function keyword
2.place fat arrow between parenthis and curly brackets

// arrow functions
var add = (x1,x2) => {
return x1 + x2 ;
}

add(6,8); // o/p 14

Ex.1

/*
var hello =() => {
console.log("hello everyone");
}

hello();
*/

Ex.2 When you single statement inside function then curly brackets are optional.
we can write the function as below
/*
var hello = () => console.log("hello everyone");
hello();

*/

Ex.3
When you have single return statament inside then return statement and
Curly brackets are optional

/*
var square = (x:number) => {
return n * n ;
}
console.log(square(10));

var square = (x:number) => x * x ;


console.log(square(5)); o/p 25
console.log(square(15)); 0/p
*/

Ex.4 When there is no parameters then () empty parenthis is mandatory.

var message = () => console.log("Hello Everyone")

message();

Ex.5 Write arrow function to check whether the given number is even or not.

/*
var isEven = (x:number) => {
if(x%2 == 0){
console.log(`${x} is Even Number`);
}else{
console.log(`${x} is odd number`);
}
}

isEven(23);

*/

Assignment
--------
1.Check whether given number is palindrome or not
Ex. 123
read in rever direction 321
O/p -> No

Ex.121
O/p Yes

Logic:

123 % 10 = 3;
123 / 10 = 12
12 % 10 = 2 ;
12 / 10 = 1
1 % 10 = 1

123

string + number = string


var num:number = 123 ;
var result : string = "";
var num1:number = num ;

while(num > 0){


var rem = num % 10;
num = Math.floor(num / 10)
result = result + rem;
}

if(num1 === Number(result)){


console.log("Palindrome")
}else {
console.log("Not Palindrome");
}

2.check whether the given number is prime number or not


For Ex.
11 -> is prime number

=====================================================
21-02-2023

Scopes in TypeScript
--------
There are 2 scopes
1.global scope
2.local scope

1.global scope :
---------
the variables which are declared outside the function are having global scope
and these variables
available for all functions.

For Ex.
var x = 10 ;

function f1(){
console.log(x);
}

function f2(){
console.log(x);
}

f1();
f2();
console.log(x);

O/p
--
10
10
10

2.Local Scope
--------------
the variables which are declared inside the function are having local scope and
available for that
function only.
Outside the function we cannot access these local scoped variables.

Ex.2
function f1(){
var x = 20 ;
console.log(x)
}

f1(); // o/p 20
console.log(x); // error variable x is not defined.

-----

Ex.3
--------

/*
var x:number = 20 ;
function f1(){
var x:number = 30 ;
console.log(x);
}

function f2(){
console.log(x);
}

f1();
f2();
console.log(x);

*/

o/p
30 // function f1 has seprate local variable with name hence o/p 30
20 // global variable o/p
20 // global variable x hence o/p 20

Ex.4
------
var x:number = 20 ;
function f1(){
var x:number = 30 ;
console.log(x);
}

function f2(){
console.log(x);
}

f1();
f2();
console.log(x);

O/p
---
20
30
30

Ex.5
---
var x:number = 30 ;
function f1(){
x = 20 ;
console.log(x);
}

function f2(){
var x : number = 50 ;
console.log(x);
}

f2(); // 50
f1(); // 20
console.log(x); // 20

=====================================================================

var,let,const
---------------

function f1(){
const message:string="Welcome";
if(true){
const message2:string="Welcome to our website";
console.log(message);
console.log(message2);
}
console.log(message);
console.log(message2);
}

f1();

======================================

difference between var,let,const ?

var
------------
For Ex.
var message:string;
message="Good Morning";

//or
var message:string="Good Morning"; // declaration & Initialization
message = "Hi Everone"; // reinitialization
console.log(message);

var message:string="Hello"; // redeclaration is possible


console.log(message);

1.If you declare variable with var keyword then ititialization , reinitialization
and
redeclaration is possible in any scope i.e either in global or local

2.var keyword is function scoped.


variable declared with var keyword has access within that function.
if we declare outside the function then they are available everywhere.

/* var has function level scope


function f1(){
var x:number = 20;
if(x == 20){
var num1:number=30;
console.log(x);
}
console.log(num1);
console.log(x);
}

f1();

*/

let
---------------------------

1.if you declare variable with let keyword then initialization,reinitialization is


possible in same scope
but redeclaration is not possible in same scope.

For ex.
let message:string="Good Morning"; // declaration and initialization
message = "Hi everyone"; // reinitialization
console.log(message);
let message:string="Good Afternoon"; // error redeclaration is not possible

2.redeclaration is possible in different scope.


For Ex.
let z:number = 10 ;
function f1(){
let z:number = 40 ;
console.log(z);
}

f1();
console.log(z);

3.let keyword has block level scope


if you try to access let variabe outside the block it will immediately give an
error.

Ex.1
/*
function f1(){
let x : number = 20 ;
if(x == 20){ // assuming if condition is true
console.log(x); // o/p 20
}
console.log(x); // o/p
}

f1();
*/

Ex.2

/*
function f1(){
if(true){
let x : number = 20 ;
console.log(x);
}
console.log(x); // error outside the block we cannot access let variabe x
}

f1();

*/

const
------
1.If you declare variable with const keyword then initialization is possible
but reinitialization of const variabe is not possible.
redeclaration is also not possible in same scope.

const message:string ="Good Morning";// declaration and initialization


console.log(message);;
message = "Good Afternoon" ; // reInitialization is not possible
const message:string = "Welcome" ; // redeclaration is not possible

2.redeclaration is possible in different scope.

For Ex.
let z:number = 10 ;
function f1(){
let z:number = 40 ;
console.log(z);
}

f1();
console.log(z);

3.const has block level scope

For Ex.

Ex.1
function f2(){
const y:number = 50;
console.log(y); //o/p 50
}
f2();
console.log(y); //error

*/

Ex.2
function f2(){
if(true) { // asssume if condition is true
const y:number = 50;
console.log(y); //o/p 50
}
console.log(y); // error due to block scope
}

f2();
console.log(y); //error

*/
---------------
Note:
-----
const -> is best choice when your value of variabe does not change once initialized
var -> avoid use of var keyword because using var keyword we can redeclare ,
reassign the variables.
and also it does not support the block level scope.
let -> is the most preferable way for variabe declaration.

====================================

-----
Array Examples

1.Update array element by using index


var arr = [10,20,30,40,50];
arr[1] = 60
console.log(arr) // o/p [10,60,30,40,50]

2.Add element into array using index


var arr = [10,20,30,40,50];
arr[5] = 50 ;
console.log(arr) // o/p [10,20,30,40,50,60]

3.declare an empty array


var arr = []

Array Inbuilt Methods


----------------------
TypeScript Provides several methods which we can use with arrays

1.push()
used to add element at the end of array.
E.g
var arr = [10,20,30,40,50];
arr.push(60);
console.log(arr); // o/p [10,20,30,40,50,60]

2.pop()
used to remove last element from an array
E.g
var arr = [10,20,30,40,50];
arr.pop();
console.log(arr);// o/p [10,20,30,40]

3.unshift()
used to add element in the first position of an array.
E.g
var arr = [10,20,30,40,50];
arr.unshift(0);
console.log(arr); // o/p [0,10,20,30,40,50]

4.shift()
used to remove first element of an array.
E.g
var arr = [10,20,30,40,50];
arr.shift();
console.log(arr); // o/p [20,30,40,50]

5.indexOf
used to find the index of element of an array.
if element is not found in array then it will return -1.
var arr = [10,20,30,40,50];
var index = arr.indexOf(40);
console.log(index) // o/p 3

var indx = arr.indexOf(100);


console.log(indx); // o/p -1

6.slice()
used to get part of an array as slice.
slice(startIndex,endIndex)
it will return array elements from startIndex to endIndex - 1.

var arr = [10,20,30,40,50,60]


var newArr = arr.slice(2,4)
console.log(newArr) // o/p [30,40]

If you do not specify endIndex then slice will remove element from startIndex
till the last element of an
array

var arr = [10,20,30,40,50]


var newArr = are.slice(2);
console.log(newArr) // [30,40,50]

=============================================================================
27-02-2023

splice :
using splice method we can add element or remove elements from an array.

Syntax:
splice(startIndex,noOfElements,item,.....)

noOfElements => delete count how many elements you want to remove

-startIndex is mandatory other parameters are not mandatory based on requirement

you can add or remove.


-splice method modifies the original array.

For Ex.

Ex.1 // start index and noOfElements to be remove are provided


remove first two elements from an array.
Soln:
var arr = [10,20,30,40,50];
arr.splice(0,2)
console.log(arr); o/p [30,40,50]

Ex.2 Add two elemnts at the end of array.


var num:number[] = [20,30,60,80];

num.splice(4,0,100,120);
console.log(num);

Ex.3 Add 70 in between 60 and 80 using splice method.


var num:number[] = [20,30,60,80,100];
num.splice(3,0,70);

console.log(num);

Ex.4
// start index Provided - elements will be removed from startIndex in below
example

var arr = [10,20,30,40,50];


arr.splice(2)
console.log(arr) // O/p ->[10,20]

Ex.5 remove 60 and add 40,50 inplace of 60.


var num:number[] = [20,30,60,80,100];
num.splice(2,1,40,50)

concat()
-----------
concatinating 2 arrays and returns new array
we can concat more than 2 array also.
Ex.1
// var arr1 = [10,20,30];
// var arr2 = [40,50,60];
// var arr3 = arr1.concat(arr2);
// console.log(arr3);

Ex.2
var arr1:number[] = [10,20,30];
var arr2:number [] = [40,50,60];
var arr3:number[] = [70,80]
//concat
var newArr = arr1.concat(arr2,arr3);
console.log(newArr);

reverse
-----------
reverse the conents of the array

// var arr1 = [10,20,30,40,50];


arr1.reverse();
console.log(arr1);

we can reverse the array and store the result in new array
var arr1:number[] = [10,20,30,40,50];
var newArr:number[] = arr1.reverse();
console.log(arr1);
console.log(newArr);

sort() =>
-----------------
sort the elements of an array alphabatic or number based on its contents.
Ex.1
var num:number[] = [20,10,60,200,30,50];
var num2 = num.sort(function(a,b){
if(a > b) return 1 ;
if(a < b) return -1 ;
else return 0;
});

console.log(num2);

Ex.2 sort and store the result in another array.

var techArr:string[] = ["Angular","Html","Css","Bootstrap"];


var newTechArr = techArr.sort();

console.log(newTechArr);

array iteration
--------------------------------
there are various different functions are available in typescript array object
to iterate and process the elements.

1.forEach
we can iterate array using for each method.
For each element in the given array call the function by passing the element

n.forEach(function(element, index, array) {

});
we can also use arrow function.

n => array

here the function will be called for each element of the array by passing three
parameters
element for which it is calling(value), index of the element and total array.
-parameters are optional but based on requirement we can add parameters.
-when you perform some action on array elments forEach will modify the original
array.
-we cann't exit from forEach loop.
break statement is not allowed within the forEach it will give syntax error.

forEach vs forLoop
-----------------
1.
for loop is general purpose loop we can use everywhere
forEach method we can use only for arrays.

2.
by using for loop we can print elements in original order or rever order
but by using forEach we can iterate elements in the original order.

without forEach
------------
Iterate the below array and print productname on console.

var productArr:any = [
{productName:"Mobile",price:30000},
{productName:"Laptop",price:50000},
{productName:"Tv",price:25000},
{productName:"Table",price:4000}
]

for(var i=0;i<productArr.length;i++){
console.log(productArr[i].productName);
}

using forEach
-------------
anonymous function
----------
productArr.forEach(function(item:any,index:number){
console.log(item.productName);
})

arrow function -------------


shortest syntax:

productArr.forEach((item:any,index:number)=>console.log(item.productName));

Assignment
-------------
var productArr:any = [
{productName:"Mobile",price:30000},
{productName:"Laptop",price:50000},
{productName:"Tv",price:25000},
{productName:"Table",price:4000}
]

1.using forEach iterate the above array and store the products whose price is
greater than "25000" in newArray.

Ex.2
var arr:number[] = [2,3,7,9,10];
print the even number on console using forEach method.

Ex.3
------
using forEach
var arr:string[] = ['green','red','black']

o/p:
1 choice is green
2 choice is red
3 choice is black.

==============================================================================
28-02-2023
----------------

2.Filter
-----------
-filter method will filter the element based on some condition and it will creates
new array with element.
-filter method doesn't modify the original array but it returns new array.

using anonymous function:


---------------------
Ex.

var productArr:any = [
{productName:"Mobile",price:30000,category:"Mobiles"},
{productName:"Table",price:4000,category:"furniture"},
{productName:"Laptop",price:50000,category:"electronics"},
{productName:"Tv",price:25000,category:"electronics"},
]

var newArr = productArr.filter(function(item:any){


if(item.category == "electronics"){
return true;
}else {
return false ;
}
})

console.log(newArr);

using Arrow function(shortest syntax)


------------
var newArr = productArr.filter((item:any)=> item.category == "electronics");
console.log(newArr)

map
------------
map is used for mapping each element of the array into a different value
map function creates new array from calling a function for every array element
map will not modify the original array.

Ex.1 //multiply by 5 to each element of array.

var arr = [10,20,30,40,50] ;


var newArr = arr.map((el:number)=> el*5);

console.log(arr); // o/p [50,100,150,200,250]


console.log(newArr); // o/p [50,100,150,200,250]

Ex.2 give 100 discount on each product


i.e substract 100 from product price.

var productArr:any = [
{productName:"Mobile",price:30000,category:"Mobiles"},
{productName:"Table",price:4000,category:"furniture"},
{productName:"Laptop",price:50000,category:"electronics"},
{productName:"Tv",price:25000,category:"electronics"},
]

using anonymous function


------------
var newArr = productArr.map(function(el:any){
el.price = el.price - 100;
return el ;
})

console.log(newArr);

using arrow function


--------------
var newArr = productArr.map((el:any)=>{
el.price = el.price - 100;
return el ;
})

console.log(newArr);

Ex.3 retrieve the category from the productArr into the new array
--------

var categoryArr:string[] = [];

using anonymous function


--------------------
categoryArr = productArr.map(function(item:any){
return item.category;
})
using arrow function
------------------
categoryArr = productArr.map((item:any)=> item.category);

reduce()
==========
reduce() method used to reduce elements/values of array into a single value.

Ex.1 find the sum of array elements using reduce method.


var num:number[] = [10,20,30,40,50];

var result = num.reduce(function(accumulator:number,currentvalue:number){


return accumulator + currentvalue;
})

console.log(result);

Ex.2 find the total price of products which are in the "productArr".

var productArr:any = [
{productName:"Mobile",price:30000,category:"Mobiles"},
{productName:"Table",price:4000,category:"furniture"},
{productName:"Laptop",price:50000,category:"electronics"},
{productName:"Tv",price:25000,category:"electronics"},
]

using anonymous function


------------------
var totalPrice = productArr.reduce(function(accumulator:number,currentVal:any){
return accumulator + currentVal.price ;
},0)

using arrow function


-------------------------
var totalPrice = productArr.reduce((accumulator:number,currentVal:any)=>accumulator
+ currentVal.price ,0)

Variables and data types(special data types)


user defined data types
interface
Object,Arrays,nested Object,array of Objects
Operators
Statements
Loops
Functions
1.named function
2.anonymous function
3.arrow function
Scope
1.local scope 2.global scope
var,let,const
Array Inbuilt method
1.push 2.pop 3.unshift 4.shift 5.indefOf 6.slice 7.splice 8.concat 9.reverse()
10.sort
forEach
map
filter
reduce

========================================================
1-03-2023

OOP

----
Object oriented programming

class :
-is template or structure to create objects.
-is nothing but collection of variables or methods which are used to perform
particular
functionality.

Object :
- is nothing but an instance of class.
- if you want to access variables and methods related to particular class then we
must create
an object for that class.

syntax :
class className{
}

class is keyword used to create classes.


you can give any class Name.

For ex.

class Car {
message:string="Good Morning";

drive() {
console.log("car started");
};
}

var carObj = new Car();


carObj.drive()

Note:function keyword is not required while declaring function in class.

- in order to create an object for above class we need to use new keyword followed
by classname.
- create object and store in one variable and use that variable to access variables
and methods.
if we do not store in variable then everytime we need to use object to call any
variables
or methods.

var sampleObj = new sample();


sampleObj.sayHello();

Member variables/properties or global variables :


-the variable which are declared outside the function has global scope.
-member variables/properties we need to declare directly in the class.
-member variables/properties can be accessed everywhere in the class. i.e in any
methods.
-inside the class when you declare a variable then var keyword is not required.
but you declare local variables using var,let and const.

"this" keyword
- always reference to the current object.
- declared variables or methods if we want to access in another method of same
class
then we need to use this keyword.

Ex.2

class Demo {
message:string = "";

createMessage(){
this.message = "Good Morning";
}

displayMessage(){
console.log(this.message);
}
}

var obj = new Demo();


obj.createMessage();
obj.displayMessage();

//we can create multiple objects for same class and each class has its own copy of
variables
and methods.
var obj2 = new Demo();
obj2.createMessage();
obj2.displayMessage();

=====================

1.create one class Book


take 2 properties book_name and price
set these two properties in one method
and get the values from another method.
Method with parameters example :
-------------------------
class Product {
productName:string="";
price:number=0;
quantity:number = 0;
totalPrice:number = 0

setProductName(p_name:string){
this.productName = p_name;
}

calTotalPrice(price:number,quantity:number){
this.price = price ;
this.quantity = quantity ;
this.totalPrice = this.price * this.quantity ;

printPorductDetails(){
console.log(this.productName + " " + this.totalPrice);
}
}

var productObj = new Product();


productObj.setProductName("Mobile");
productObj.calTotalPrice(10000,4);
productObj.printPorductDetails();

var productObj2 = new Product();


productObj.setProductName("Laptop");
productObj.calTotalPrice(20000,2);
productObj.printPorductDetails();

=======================================
02-03-2022

class Demo {
message:string = "";

setMessage(message:string){
this.message = message;
}

printMessage(){
console.log(this.message);
}
}

var obj1 = new Demo();


obj1.setMessage("Welcome");
obj1.printMessage();
var obj2 = new Demo();
obj2.setMessage("Good Morning");
obj2.printMessage();

setter and getter methods

class Person {
firstName:string="";
lastName:string="";
age:number=0;

setAge(age:number){
if(age > 0 && age < 100){
this.age = age
}else {
throw new Error("Please enter the valid age");
}

var obj1 = new Person();


obj1.firstName = "Sam";
obj1.lastName = "Sharma";
console.log(obj1.firstName);
obj1.setAge(200);

var obj2 = new Person();


obj2.firstName = "Mike";

=============================
02-03-2023

constructor
-----------
is used for instantation i.e to create the object for the class.
every class have constructor implicitly or explicitly.
the job of constructor is to create the object for the class. at the time of
creating the object if we want to perform some initilization logic
or some additional actions or some extra work you want to perform that we can write
in constructor.
if class contains constructor then constructor will excute automatically we dont
need to call constructor externally.
it is special method.
constructor rules are same as method we can pass parameter to the counstructor.

Ex.

class Person {
firstName:string="";
lastName:string="";
age:number=0;

//without contructor
// setPersonalDetails(first_name:string,last_name:string,age:number){
// this.firstName = first_name ;
// this.lastName = last_name ;
// this.age = age ;
// }

printPersonalDetails(){
console.log(`${this.firstName} ${this.lastName} ${this.age}`);
}

// with contructor
constructor(first_name:string,last_name:string,age:number){
this.firstName = first_name ;
this.lastName = last_name ;
this.age = age ;
}
}

// without constructor
var obj = new Person();
//obj.setPersonalDetails("Virat","Kohli",36);
obj.printPersonalDetails();

//With Constructor
var obj = new Person("Virat","Kohli",36);
obj.printPersonalDetails();

setters and getter method


--------------------
we can control the property value using setter and getter method
without setter and getter method also we can store the value in property but we
dont have control on the property value.
setter -> is used to store the value in property
getter -> is used to get the value from property
for ex.
in below ex we want age of person should be between 0 to 100.

class Person {
firstName:string="";
age:number = 0

var obj1 = new Person();


obj1.age = 200 ; // we dont have control on the property value we can assign any
value
obj1.firstName = "Sam";

//using setter and getter

class Person {
firstName:string="";
age:number = 0

setAge(age:number){
if(age >0 && age <100){
this.age = age ;
}else {
throw new Error("Please enter the valid age")
}
}
}

var obj1 = new Person();


obj1.setAge(90) // OK
obj1.setAge(120) // error

static members
------------------
class can have static or non static members/instance members

instance variables->
value of the instance variable is varied from object to object.
for every object seprate copy will be created
within the class we can access instance variable using "this".

static variables
-------
if the value of the variable is not varied from object to object such type of
variable we need to declare using static modifier.
incase of instance variables for every object seprate copy will be created but
incase of static variables for entire one class only
one copy will be created and same copy will be reused for every object of the
class.
static variables/methods we can access using class name.

class Demo {
static staticCounter:number = 0;
nonStaticCounter:number = 0 ;

constructor(){
this.nonStaticCounter = this.nonStaticCounter + 1 ;
Demo.staticCounter = Demo.staticCounter + 1 ;
}

printCounter(){
console.log(Demo.staticCounter,this.nonStaticCounter);
}

var obj1 = new Demo();


obj1.printCounter() // 1,1

var obj2 = new Demo();


obj2.printCounter() // 2,1
Ex.2

class Employee {
emp_name:string="";
emp_designation:string="";

company_name:string = "FaceBook";

constructor(empName:string,desi:string){
this.emp_name =empName ;
this.emp_designation = desi;

// this.company_name = companyName;
}

saveEmployeeDetails(){
console.log(this.emp_name + " " + this.emp_designation + " " +
Employee.company_name);
}

var employeeObj = new Employee("Mike","Software developer");


employeeObj.saveEmployeeDetails();

var employeeObj2 = new Employee("John","Manager");


employeeObj2.saveEmployeeDetails();

==============================================================
Inheritance:
-----------
Inheritance is nothing but an inherit the properties and methods from some other
class

without rewriting code again we can inherit the properties or methods from one
class to another class.

-we need to use "extends" keyword to inherit the functionality


from one class to another class.

from which class we are inheriting the properties or method that class is called
Parent class.
to which class we are inheriting the properties are called child class.

-the main advantages of Inheritance is code reusability

Rule:
-we can access all the parent class methods and variables through child class
but we cannot access child class related variables and methods through parent
class.
-Any class can extends only one class at a time and can't extends more than one
class

Ex.1
class Sample {
sayHello(){
console.log("Hi everyone...Good Morning");
}
}

class Test extends Sample {

var obj = new Test();


obj.sayHello();

Ex.2
class Person {
name:string="";
age:number=0;

setDetails(nameOfPerson:string,ageOfPerson:number){
this.name = nameOfPerson ;
this.age = ageOfPerson ;
}

printInformation(){
console.log("Name Of Person is "+this.name + " Age is " + this.age);
}

class Employee extends Person{

var obj = new Employee();


obj.setDetails("Rohit",40);
obj.printInformation();

Ex.3
class Person {
name:string="";
age:number=0;

setDetails(nameOfPerson:string,ageOfPerson:number){
this.name = nameOfPerson ;
this.age = ageOfPerson ;
}

printInformation(){
console.log("Name Of Person is "+this.name + " Age is " + this.age);
}

class Employee extends Person{


employeeId:number=0;
salary:number = 0;

setEmployeeDetails(e_id:number,salary:number){
this.employeeId = e_id;
this.salary = salary;
}

printEmployeeInformation(){
console.log(this.name + " " + this.age + " " + this.employeeId + " " +
this.salary)
}
}

var obj = new Employee();


obj.setDetails("Rohit",40);
obj.setEmployeeDetails(1,20000);
obj.printEmployeeInformation();

var personObj = new Person();


personObj.setEmployeeDetails() // we cannnot access child class related properties
and method in parent class.

Ex.4
----------
class Person {
name:string="";
age:number=0;

constructor(nameOfPerson:string,ageOfPerson:number){
this.name = nameOfPerson ;
this.age = ageOfPerson ;
}

printInformation(){
console.log("Name Of Person is "+this.name + " Age is " + this.age);
}

class Employee extends Person{

var obj = new Employee("Sam",40);


obj.printInformation();

Super method
--------------
super()
-it is used to call parent class constructor from child class.
-If parent class constructor accepts few arguments then that parameters we need to
pass
in super method()
-super() should be the first line in constructor.
-If the child class has constructor method then calling super() is mandatory.
-If the parent class doesn't have the constructor and child class has constructor
then we need to invoke the super() without any parameters.

Ex.1
-----------

class Person {
name:string="";
age:number=0;

constructor(nameOfPerson:string,ageOfPerson:number){
this.name = nameOfPerson ;
this.age = ageOfPerson ;
}

printInformation(){
console.log("Name Of Person is "+this.name + " Age is " + this.age);
}

class Employee extends Person {

constructor(name:string,age:number) {
super(name,age);
}
}

var obj = new Employee("Sam",40);


obj.printInformation();

Ex.2
class Person {
name:string="";
age:number=0;

constructor(nameOfPerson:string,ageOfPerson:number){
this.name = nameOfPerson ;
this.age = ageOfPerson ;
}
}

class Employee extends Person {


employeeId:number = 0 ;
constructor(name:string,age:number,empl_id:number) {
super(name,age);
this.employeeId = empl_id ;
}

printEmployeeDetails() {
console.log("Name Of Person is "+this.name + " Age is " + this.age + "
Employee Id is " + this.employeeId);
}
}

var obj = new Employee("Sam",40,1);


obj.printEmployeeDetails();

==================================================

Access Modifiers :
------------------
1.Public Modifier
-------
-If we declare any property or method with public modifiers then we can access that
method
and property anywhere in the class.
-by default(if we do to specify the modifier) then that properties and method are
public.
for ex.
class A {
name:string ;

setName(nameOfPerson:string){
this.name = name ;
}

var obj = new A();


obj.name="John" // it will not give any error due to public property
obj.setName(); // it will not give any error due to public method

2.Private Modifier
---------
-If we declare any property or method with private modifiers then we can access
that
method or property within the class only.
-we cannot access the property or method outside the class.
if we try to access outside the class then immediately it will give an error.
-we cannot access even in child class(derived classes).

class A {
private name:string ;

private setName(nameOfPerson:string){
this.name = name ;
}

sayHello(){
console.log("Hi Everyone")
}

var obj = new A();


obj.name = "John" // compile time error as property is private
obj.setName() // method is private hence compile time error
obj.sayHello() // method is public hence we can access.

3.Protected Modifier
-------------
If we declare any property or method with protected modifier then that property or
method will
not be available outside the class but we can access in child class or derived
classes.

class A {
protected name:string ;

protected setName(nameOfPerson:string){
this.name = name ;
}

sayHello(){
console.log("Hi Everyone")
}
}

var obj = new A();


obj.name="Mike" // compile time error due to protected modifier
obj.setName() // compile time error
obj.sayHello() // no error it will display output.

class B extends A {

displayName(){
this.name = "Sam"; // we can access protected modifiers variable in child class
//or
this.setName("David") // we can access protected modifiers method in child class
}
}

var obj = new B();


obj.name = "John"; // compile time error
obj.setName(); // compile time error

Ex.

readOnly
----------
- "readOnly" is keyword used at the time of variable declaration.
-whenever we declare any property/variable with "readOnly" access modifier then you
cannot modify
its value in normal method.
-you can assign value either at the time of declaration or in constructor.

readOnly vs const
-------------------
1. "const" used to declare variable inside the function when we have class.
"readOnly" used to declare properties inside the class.

2. "const"- at the time of declaration it is mandatory to initialize or assigning


value.
"readOnly" can be declared without assigning value.we can initialize inside
constructor.
3. "const" value cannot be reassigned but "readOnly" can be reassigned but only in
constructor.

Ex.

class Test {
readonly message:string="good morning";

constructor(){
console.log(this.message);
}

// setMessage(msg:string){
// this.message = msg ; // compile time error we cannot initialize or
reinitialize its value.
// console.log(this.message);
// }

const testObj = new Test();


message = "Welcome" // error we cannot update the value.
testObj.setMessage("Good Morning"); // compile time error

Ex.2
----

class Employee {
private empId:number=0;
private emplName:string="";
readonly designation:string="Software developer";

constructor(id:number,name:string){
this.empId = id ;
this.emplName = name ;
}

saveEmplInfo(){
console.log("Employee Id " + this.empId + "Employee Name "+this.emplName +
"Designation is " + this.designation)
}
}

var employeeObj1 = new Employee(1,"David");


employeeObj1.designation = "Angular Developer" // we cannot change

var employeeObj2 = new Employee(2,"Mike");

===================================================================================
=========================================
06-03-2023

Interface
-------------

interface Product {
productName:string;
price:number,
quantity:number,
total():number,
print():void
}

var productObj:Product = {
productName:"Mobile",
price:20000,
quantity:2,
total:function(){
return this.price * this.quantity
},
print:function(){
console.log(this.productName + " " + this.price);
}
}

Ex.2
------
interface IProduct {
productName:string;
price:number;
quantity:number;
total():number;
printProductDetails():void
}

class Product implements IProduct {


productName="";
price=0;
quantity=0;
rating:number =0;
constructor(p_name:string,price:number,quantity:number){
this.productName = p_name ;
this.price = price ;
this.quantity = quantity;
}

setRating(rating:number){
this.rating = rating ;
}

total(){
return this.price * this.quantity;
}

printProductDetails(){
console.log(this.productName + " " + this.price + " " +this.rating);
}

var productObj = new Product("Mobile",20000,2);


console.log(productObj.total());
productObj.setRating(4.2);
productObj.printProductDetails();
Ex.3
---------
interface IEmployee {
employeeId:number ;
employeeName:string;
designation?:string;
printEmployeeDetails():void

class Employee implements IEmployee {


employeeId=0;
employeeName="";

constructor(e_id:number,e_name:string,designation:string){
this.employeeId = e_id ;
this.employeeName = e_name;
// this.designation = designation ;
}

printEmployeeDetails(){
console.log(this.employeeId + " " + this.employeeName)
}

------
abstraction
-----------------
-abstract class contains some predefined logic and properties which we can
customize according to our requirements.
-abstraction is nothing but hide internal implementation and show just set of
service/functionality.
by using abstract class we can implements abstraction.
-we cannot create the object for the abstract class as abstract class contains
incomplete methods.
-if a class contains any abstract methods i.e incomelete method and we are not
responsible to provide implementation for this
methods then we need to mark this class as abstract.
-if we want to access methods and variables related to abstract class we need to
implement inheritance concept.

interface ILoan {
loanAmount:number;
tenure:number;
rateofInterest:number;
loanPurpose?:string;
getRateOfInterest():number;
printLoanDetails():void;
}
abstract class LoanMember implements ILoan {
loanAmount=10000;
tenure =24;
abstract rateofInterest: number;
abstract getRateOfInterest():number;

printLoanDetails(){
console.log(this.loanAmount + " " + this.tenure);
}
}

class LoanHolder extends LoanMember {


rateofInterest: number = 10;
getRateOfInterest(): number {
// business logic
return this.rateofInterest;
}

var obj = new LoanHolder();


obj.printLoanDetails();

polymorphoism
-----------

method overloading :
------------

method overriding
------
class Demo {

performAction(x1:number,x2:number){
return x1 + x2 ;
}
}

class AnotherDemo extends Demo {


performAction(x1: number, x2: number) {
return x1 * x2;
}
}

var obj = new AnotherDemo();


var result = obj.performAction(10,20);
console.log(result);

var obj2 = new Demo();


var result1 =obj2.performAction(10,20);
console.log(result1);

===================================================================================
================

08-03-2023
Polymorphism :
--------------
same name with different functionality is nothing but polymorphism

two types
1.Method Overloading
2.Method overriding

1.Method Overloading
-> two method are said to be overload if they have same name with different
arguments.
- typescript compiler does not support the method overloading
- Javascript doesnot support the method overloading

2.Method Overriding
-> Due to inheritance concept parent class method and variables are available to
child class.
but child class is not satisfied with parent class method implementation then
we can re declare
or redefine parent class method in child class it its own way.

-method name , method argument , argument types should be same while


overriding.

Ex.
class Demo {

performAction(x1:number,x2:number){
return x1 + x2 ;
}
}

class AnotherDemo extends Demo {


performAction(x1: number, x2: number) {
return x1 * x2;
}
}

var obj = new AnotherDemo();


var result = obj.performAction(10,20);
console.log(result);

var obj2 = new Demo();


var result1 =obj2.performAction(10,20);
console.log(result1)

========= Installation
********************************************
nodeJs =>
is not programming language
it create environment where you can run your javascript code outside browser.

https://nodejs.org/en/download/
node -v => check whether node is installed or not.
when you install nodejs then automatically npm(node package manager) will gets
downloaded.

https://www.npmjs.com/ =>
npm => node package manager
it is used to download (packages,frameworks) which are in the remote
repository.

npm install -g typescript

tsc -v

Visual Studio code download


-----------------
https://code.visualstudio.com/Download

compile code using below command


tsc fileName.ts

Run TypeScript Code


node fileName.js

or

TypeScript Playground
https://www.typescriptlang.org/play

=========================
09-03-2023

whenever we are building a large application we cannot store everything in single


file..we need to store in multiple files.
hence depending upon our functionlity we can break the code into multiple files.

module
-----
is collection of variables,functions,templates,classes/components.

advantages
----
1.we can reuse the function,classes,interfaces whenever it is required.

by default if u define anything in file we can access only inside the file if we
want to access those functionlity outisde the current file then we need
export,import.
export -> is used to export interface,classes,function from one file to another.
import ->is used to import the file in current file.

syntax:
we can export interface,classes,function,properties
for ex.
export interface IPerson,
export class Person ,
export function add(n1:number,n2:number);

we can import in another file using below syntax


import { } from "path"

below are the steps to create module


1.create folder with any name for ex.home

2.create multiple subfolder under it


for ex.
home
-interfaces
-classes/components
-templates
-functions

3.Go to each folder and create file


for ex.
interfaces -> IProduct.ts
classes -> Product.ts

4.Write the logic as per the requirements

5.create one test file to test this module


test.ts

Ex.

Ex.
home
-interfaces
-IProduct.ts

export interface IProduct {


productName:string;
price:number;
quantity:number;
total():number;
print():void;
}

home
-templates
-ProductTemplate.ts

import { IProduct} from "../interfaces/IProduct";

export abstract class ProductTemplate implements IProduct {


quantity: number = 2;
productName: string = "TV";
price: number = 20000;

total(): number {
return this.price * this.quantity;
}

abstract print(): void ;

home
-classes
-product.ts

-----
import { ProductTemplate} from "../templates/ProductTemplate";

export class Product extends ProductTemplate {


print(): void {
console.log("Product Name "+this.productName + "Price "+this.price +
"Quantity "+ this.quantity);
}

home
-functions
-function.ts

export function add(n1:number,n2:number){


console.log(n1 + n2);
}

test.ts
-----------
import { Product} from "./home/classes/Product";
import {add} from "./home/functions/function";

var obj = new Product();


var result = obj.total();
console.log(result);
add(10,20);

enums
------
whenever we are working in real world application we need to deal with contstans.

enums is nothing but collection of constants .


constants can be string or number

syntax:
enum name{

Ex.
enum directions{
North = "N",
South = "S",
East = "E",
West = "W"

const direction:string=directions.North;
console.log(direction);

Ex.2
with the enums we can get the value from keyname or from value we can get the key
name.
enumName.key => value
enumName[value] => key

in below ex.

enum Weekdays {
Sunday = 0 ,
Monday = 1 ,
Tuesday = 2 ,
Wednesday = 3 ,
Thursday = 4 ,
Friday = 5 ,
Saturday = 6
}

console.log(Weekdays.Tuesday); // 2
console.log(Weekdays[3]) // Wednesday

const todaysDate:any = new Date();


todaysDate.getDate() -> will return the todays date(day of month i.e 1 to 31)
todaysDate.getDay() -> it will return the day of week(0 to 6)
todaysDate.getMonth() -> will return month (i.e from 0 to 11);

console.log(Weekdays[todaysDate.getDay()]) //

Ex.3
-----
numeric constans autoincrement the value depending upon previous value.
in below ex We are not giving value to Monday but depending upon the previous value

Monday is assigned to 1.

enum Weekdays {
Sunday = 0 ,
Monday,
Tuesday,
Wed,
Thur,
Fri,
Sat
}

console.log(Weekdays.Tuesday); // 2
console.log(Weekdays.Monday); // 1

You might also like