Professional Documents
Culture Documents
is application which can be accessed from anywhere and provides services over the
internet.
For ex gmail.com,facebook.com,amzon, irctc.
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.
==============
What is Angular ?
angular is client-side-framework used to develop dynamic web application.
multi-page application.
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.
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 add(x,y){
console.log(x+y);
}
add(5,6); //o/p 11
add('2',3);
4.
.ts extension
.js extenion
5.
typescript will give error at compile time
javascript will give error at runtime.
data types :
1.number
2.string
3.boolean
1.number => number is data type which is used to represent numeric data.
for ex.
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 .
2.string
It is built data type.
used to represent or store alphabets or textual data.
For Ex.
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 ;
//or
var messagelength1:number = message1.length ; //declaration and initialization
console.log(messagelength1);
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];
//blank array
var list:string[] = [];
console.log(list.length); // 0
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
Object
------
by using arrays we can store group of data/values in single variable but we cannot
store data in key-value pairs.
Ex.1
var playerObj : any = {
firstName : "Virat",
lastName : "Kohli",
age : 35
}
console.log(playerObj.age);
console.log(personObj.address.country);
console.log(personObj.address.city);
Ex.2
var personObj : any = {
firstName : "Sam",
mobileNo: 8989898989,
gender: "Male",
address : addressObj
}
console.log(personObj.address.country);
console.log(personObj.address.city);
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
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);
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,
}
]
//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
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.
or
var x:number;
console.log(x);// 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;
Operators
------------------------
1.arithmetic operators
+,-,*,%,/ , ++ , --
2.comparision operators
< , <= , > , >= , == , === , != , !==
3.logical operators
&& , || , !
1.Arithmetic operators
-------------------------
100 / 20 = 5
Ex.
var x1:number = 100 ;
x1 = x1 + 10 ; // adding 10 in x1 variables
console.log(x1);
console.log(x - y);
console.log(x * y);
console.log(x / y); // 2;
var x : number = 20 ;
var y : number = 10 ;
var result :number = x - y ;
console.log(result);
--------------
++ , --
"++"
is used to add 1 to value.
"--"
is used to decrement the value by 1.
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); //
=== (Strict equality operator)=> value and data type is important while comparing.
"==" 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';
// == && ===
---------------
"!=" 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';
// != && !==
//== ===
===========================================================================
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.
Note:
false || true => true
================================
var a:number = 20 ;
var b:number = 30 ;
var x:number = 0 ;
console.log(!a);
console.log(!x);
Ex.
var a:number = 20 ;
var b:number = 30 ;
Ex.
var message:string="";
console.log((message.length > 0) || !0);
Ex.
console.log(null == undefined); // true values are false
Note:
1. 0 (Zero),null,undefined,""(empty string) is always considered as false.
value is false.
=========================================================================
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
var age:number = 10 ;
Ex.2 show eligible message when user age is greater than 18 and voterId available
var age:number = 30 ;
var isVoterCardAvailable:string = "No";
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";
Assignments
--------
1.Check whether the given number is positive number or not.
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 ;
4.
var userId : string = "test123";
var password:string = "welcome123";
==============================================================================
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
}
Ex.
var x:number = 1 ;
while(x <= 10){
console.log("Good Morning");
x++ ;
}
Ex.2
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
}
---------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
console.log(5 * i = )
var result = 0 ;
for(var n1=0;n1<arr.length;n1++){
result = result + arr[n1];
}
console.log(result);
console.log("Hello");
//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
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.
================================================================
// 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.
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 ;
}
}
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 ;
}
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 ;
}
==================================
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 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
}
}
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]);
Ex.
function add(x1:number,x2:number){
return x1 + x2 ;
}
function sum(arr:number[]){
var result : number = 0 ;
for(var i=0;i<arr.length ; i ++){
result = result + arr[i]
}
return result ;
}
Ex.3
function calculateTotalprice(amount:number,discount:number){
return amount - discount;
}
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
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
}
/*
var hello = function(){
console.log("hello everyone");
}
hello()
*/
/*
//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);
*/
// 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));
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
=====================================================
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();
======================================
var
------------
For Ex.
var message:string;
message="Good Morning";
//or
var message:string="Good Morning"; // declaration & Initialization
message = "Hi Everone"; // reinitialization
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
f1();
*/
let
---------------------------
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
f1();
console.log(z);
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.
For Ex.
let z:number = 10 ;
function f1(){
let z:number = 40 ;
console.log(z);
}
f1();
console.log(z);
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.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
6.slice()
used to get part of an array as slice.
slice(startIndex,endIndex)
it will return array elements from startIndex to endIndex - 1.
If you do not specify endIndex then slice will remove element from startIndex
till the last element of an
array
=============================================================================
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
For Ex.
num.splice(4,0,100,120);
console.log(num);
console.log(num);
Ex.4
// start index Provided - elements will be removed from startIndex in below
example
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
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);
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
});
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);
})
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.
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"},
]
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.
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"},
]
console.log(newArr);
console.log(newArr);
Ex.3 retrieve the category from the productArr into the new array
--------
reduce()
==========
reduce() method used to reduce elements/values of array into a single value.
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"},
]
========================================================
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{
}
For ex.
class Car {
message:string="Good Morning";
drive() {
console.log("car started");
};
}
- 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.
"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);
}
}
//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();
=====================
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);
}
}
=======================================
02-03-2022
class Demo {
message:string = "";
setMessage(message:string){
this.message = message;
}
printMessage(){
console.log(this.message);
}
}
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");
}
=============================
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();
class Person {
firstName:string="";
age:number = 0
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")
}
}
}
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);
}
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);
}
==============================================================
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.
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.
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");
}
}
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);
}
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);
}
setEmployeeDetails(e_id:number,salary:number){
this.employeeId = e_id;
this.salary = salary;
}
printEmployeeInformation(){
console.log(this.name + " " + this.age + " " + this.employeeId + " " +
this.salary)
}
}
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);
}
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);
}
constructor(name:string,age:number) {
super(name,age);
}
}
Ex.2
class Person {
name:string="";
age:number=0;
constructor(nameOfPerson:string,ageOfPerson:number){
this.name = nameOfPerson ;
this.age = ageOfPerson ;
}
}
printEmployeeDetails() {
console.log("Name Of Person is "+this.name + " Age is " + this.age + "
Employee Id is " + this.employeeId);
}
}
==================================================
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 ;
}
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")
}
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")
}
}
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
}
}
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.
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);
// }
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)
}
}
===================================================================================
=========================================
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
}
setRating(rating:number){
this.rating = rating ;
}
total(){
return this.price * this.quantity;
}
printProductDetails(){
console.log(this.productName + " " + this.price + " " +this.rating);
}
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);
}
}
polymorphoism
-----------
method overloading :
------------
method overriding
------
class Demo {
performAction(x1:number,x2:number){
return x1 + x2 ;
}
}
===================================================================================
================
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.
Ex.
class Demo {
performAction(x1:number,x2:number){
return x1 + x2 ;
}
}
========= 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.
tsc -v
or
TypeScript Playground
https://www.typescriptlang.org/play
=========================
09-03-2023
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);
Ex.
Ex.
home
-interfaces
-IProduct.ts
home
-templates
-ProductTemplate.ts
total(): number {
return this.price * this.quantity;
}
home
-classes
-product.ts
-----
import { ProductTemplate} from "../templates/ProductTemplate";
home
-functions
-function.ts
test.ts
-----------
import { Product} from "./home/classes/Product";
import {add} from "./home/functions/function";
enums
------
whenever we are working in real world application we need to deal with contstans.
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
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