Web X.0 Notes-1
Web X.0 Notes-1
● In the following diagram, we can see the three layers and each of their internal
components. These layers are:
○ Language
○ The TypeScript Compiler
○ The TypeScript Language Services
● Language: It features the TypeScript language elements. It comprises
elements like syntax, keywords, and type annotations.
● The TypeScript Compiler: The TypeScript compiler (TSC) transform the
TypeScript program equivalent to its JavaScript code. It also performs the
parsing, and type checking of our TypeScript code to JavaScript code.
● The TypeScript Language Services: The language service provides
information which helps editors and other tools to give better assistance
features such as automated refactoring and IntelliSense. It exposes an
additional layer around the core-compiler pipeline. It supports some standard
typical editor operations like code formatting and outlining, colorization,
statement completion, signature help, etc.
2. Discuss TypeScript Types with suitable examples
● The TypeScript language supports different types of values.
● It provides data types for the JavaScript to transform it into a strongly typed
programing language.
● JavaScript doesn't support data types, but with the help of TypeScript, we can
use the data types feature in JavaScript.
● Following is the syntax of defining a type or data type to the variables in
typescript.
○ [Keyword] [Variable Name]: [Data Type] = [Value];
○ [Keyword] [Variable Name]: [Data Type];
● [Keyword] : It’s a keyword of the variable either var, let or const to define the
scope and usage of variable.
● [Variable Name] : It’s a name of the variable to hold the values in our
application.
● [Data Type] : It’s a type of data the variable can hold such as number, string,
boolean, etc.
● [Value] : Assigning a required value to the variable.
3. Explain variables and operators in TS
● Variables:
○ A variable is the storage location, which is used to store
value/information to be referenced and used by programs.
○ It acts as a container for value in code and must be declared before the
use.
○ We can declare a variable by using the var keyword.
○ In TypeScript, the variable follows the same naming rule as of
JavaScript variable declaration.
○ These rules are:
■ The variable name must be an alphabet or numeric digits.
■ The variable name cannot start with digits.
■ The variable name cannot contain spaces and special
character, except the underscore(_) and the dollar($) sign.
○ The let keyword is similar to var keyword in some respects, and const
is a let which prevents re-assignment to a variable.
○ var keyword is used to declare a variable
○ Variables declared in TypeScript with the var keyword have function
scope.
● Operators:
○ An Operator is a symbol which operates on a value or data.
○ It represents a specific action on working with data.
○ The data on which operators operates is called operand.
○ It can be used with one or more than one values to produce a single
value.
○ All of the standard JavaScript operators are available with the
TypeScript program.
○ In TypeScript, an operator can be classified into the following ways.
■ 1. Arithmetic operators (+,-,/,*,%,++,--)
■ 2. Comparison (Relational) operators (==,===,!=,!==,>,>=,<,<=)
■ 3. Logical operators (&&,||,!)
■ 4. Bitwise operators (&,|,^xor,~not, >>,<<,>>> bitwise right shift
with 0)
■ 5. Assignment operators (=,+=,-=,*=,/=,%=)
■ 6. Ternary/conditional operator(condition?expr1:expr2)
■ 7. Concatenation operator (+)
■ 8. Type Operator
● In to check for the existence of a property on an object.
● Delete used to delete the properties from the objects.
● Instanceof to check if the object is of a specified type or
not.
● Typeof It returns the data type of the operand.
4. Explain decision Making and loops with suitable examples.
● Decision Making
○ if statement
■ var num:number = 5
■ if (num> 0) {
■ console.log("number is positive")
■ }
○ if...else statement
■ var num:number = 12;
■ if (num % 2==0) {
■ console.log("Even");
■ } else {
■ console.log("Odd");
■ }
○ else...if and nested if statements
■ var num:number = 2
■ if(num> 0) {
■ console.log(num+" is positive")
■ } else if(num< 0) {
■ console.log(num+" is negative")
■ } else {
■ console.log(num+" is neither positive nor negative")
■ }
○ switch statement
■ var grade:string = "A";
■ switch(grade) {
■ case "A": {
■ console.log("Excellent");
■ break;
■ }
■ case "B": {
■ console.log("Good");
■ break;
■ }
■ default: {
■ console.log("Invalid choice");
■ break;
■ }
■ }
● Loops:
5. Explain TypeScript Functions
● Functions are the fundamental building block of any applications in
JavaScript.
● It makes the code readable, maintainable, and reusable.
● We can use it to build up layers of abstraction, mimicking classes, information
hiding, and modules.
● In TypeScript, however, we have the concept of classes, namespaces, and
modules, but functions still are an integral part in describing how to do things.
● TypeScript also allows adding new capabilities to the standard JavaScript
functions to make the code easier to work.
● These are the main advantages of functions.
○ Code reusability :
○ Less coding :
○ Easy to debug :
● A function without a name is known as an anonymous function.
● These type of functions are dynamically declared at runtime.
● It is defined as an expression.
● We can store it in a variable, so it does not need function names.
● We can invoke it by using the variable name, which contains function.
Multilevel Inheritance:
class Animal {
eat():void {
console.log("Eating")
}
}
class Dog extends Animal {
bark():void {
console.log("Barking")
}
}
class BabyDog extends Dog{
weep():void {
console.log("Weeping")
}
}
let obj = new BabyDog();
obj.eat();
obj.bark(); obj.weep();
9. Explain function overloading with suitable examples.
● TypeScript provides the concept of function overloading.
● You can have multiple functions with the same name but different parameter
types and return type.
● However, the number of parameters should be the same.
● Function overloading with a different number of parameters and different
types along with the same function name is not supported.
● Advantages of function overloading:
○ 1. It saves the memory space
○ 2. It provides code reusability
○ 3. It increases the readability of the program.
○ 4. Code maintenance is easy.
● Example:
function add(a:string, b:string):string;
function add(a:number, b:number): number;
function add(a: any, b:any): any {
return a + b;
}
console.log(add("Hello ", "Steve")); // returns "Hello Steve"
console.log(add(10, 20)); // returns 30
Core Features:
● Data-binding − It is the automatic synchronization of data between model
and view components.
● Scope − These are objects that refer to the model. They act as a glue
between controller and view.
● Controller − These are JavaScript functions bound to a particular scope.
● Services − AngularJS comes with several built-in services such as $http.
These are singleton objects which are instantiated only once in app.
● Filters − These select a subset of items from an array and returns a new
array.
● Directives − Directives are markers on DOM elements. Can be used to
create custom HTML tags that serve as new, custom widgets. AngularJS
has built-in directives such as ngBind, ngModel, etc.
● Templates − These are the rendered view with information from the
controller and model. These can be a single file (such as index.html) or
multiple views in one page using partials.
● Routing − It is concept of switching views.
● Model View Whatever − MVW is a design pattern for dividing an
application into different parts called Model, View, and Controller.
AngularJS implement something closer to MVVM
(Model-View-ViewModel).
● Deep Linking − Deep linking allows to encode the state of application in
the URL so that it can be bookmarked. The application can then be restored
from the URL to the same state.
● Dependency Injection − AngularJS has a built-in dependency injection
subsystem that helps the developer to create, understand, and test the
applications easily.
2. Explain AngularJS modules.
● A module in AngularJS is a container of the different parts of an application
such as controller, service, filters, directives, factories etc.
● It supports separation of concern using modules.
● Modules are used to separate logic such as services, controllers,
application etc. from the code and maintain the code clean.
● We define modules in separate js files.
● A module is used as a Main() method.
● Example:
8. Explain AngularJS controllers
● AngularJS application mainly relies on controllers to control the flow of
data in the application.
● A controller is defined using ng-controller directive.
● A controller is a JavaScript object that contains attributes/properties, and
functions.
● Each controller accepts $scope as a parameter, which refers to the
application/module that the controller needs to handle.
<script>
function studentController($scope) {
$scope.student = {
firstName: "Sachin",
lastName: "Shah",
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " +
studentObject.lastName;
}
};
}
</script>
9. Explain AngularJS scope
● The $scope in an AngularJS is a built-in object,
which contains application data and methods.
● We can create properties to a $scope object
inside a controller function and assign a value
or function to it.
● The $scope is glue between a controller and
view (HTML).
● It transfers data from the controller to view and
vice-versa.
● The view can display $scope data using an
expression, ng-model, or ng-bind directive
● An AngularJS application has a single
$rootScope. All the other $scope objects are
child objects.
● The properties and methods attached to
$rootScope will be available to all the controllers.
10. Explain AngularJS dependency injection.
● Dependency Injection is a software design in which components are given
their dependencies instead of hard coding them within the component.
● It relieves a component from locating the dependency and makes
dependencies configurable.
● It also helps in making components reusable, maintainable, and testable.
● AngularJS provides a supreme Dependency Injection mechanism.
● It provides the following core components which can be injected into each
other as dependencies.
○ Value: Value is a simple JavaScript object, which is required to pass
values to the controller during config phase.
//define a module
var myModule = angular.module("myModule", []);
//create a value object and pass it a data.
myModule.value("numberValue", 100);
myModule.value("stringValue", "abc");
myModule.value("objectValue", { val1 : 123, val2 : "abc"} );
■ Here, values are defined using the value() function on the
module.
○ Factory: Factory is a function which is used to return value. It
creates a value on demand whenever a service or a controller
requires it. It generally uses a factory function to calculate and
return the value.
○ Service: Service is a singleton JavaScript object containing a set of
functions to perform certain tasks. Service is defined using
service() function and it is then injected into the controllers.
var mainApp = angular.module("mainApp", []);
...
//create a service which defines a method square to return square
of a number.
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
});
//inject the service "CalcService" into the controller
mainApp.controller('CalcController', function($scope, CalcService,
defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
○ Constant: Constants are used to pass values at the config phase
considering the fact that value cannot be used during the config
phase.
mainApp.constant("configParam", "constant value");
Example:
<div ng-app = "mainApp" ng-controller = "CalcController">
<p>Enter a number: <input type = "number" ng-model = "number" /></p>
<button ng-click = "square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
mainApp.value("defaultInput", 5);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
</script>
</form>
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/login.html',
controller: 'loginController'
}).when('/student', {
template: '/student.html',
}).when("/courses", {
template : `<h1>Courses Offered</h1>
<ul>
<li>Machine Learning Foundation</li>
</ul>
}).otherwise({
redirectTo: "/"
});
14. Explain ng-Repeat, ng-style, ng-view. With suitable example
● ng-repeat:
<body ng-app="app">
<div ng-controller="controllerName">
<ul>
<li ng-repeat="student in students">{{student.name}}</li>
</ul>
</div>
<script>
var app = angular.module("app", []);
app.controller('controllerName', ['$scope', function ($scope) {
$scope.students = [{ name: 'John' }, { name: 'Smith' }, { name:
'Allen' }, { name: ' Johnson' }, { name: 'Harris' }, { name: ' Williams' }, {
name: 'David' }];
}]);
</script>
● ng-style
<body ng-app>
<div>
<button ng-click="style={color:'Red'}">Set Color</button>
<button ng-click="style={backgroundColor:'yellow'}">Set
Background Color</button>
<button ng-click="style={}">reset</button><br />
<span ng-style="style">Sample text</span>
</div>
</body>
● ng-view: The ng-view directive simply creates a place holder where a
corresponding view can be placed based on the configuration.
<div ng-app = "mainApp">
<div ng-view></div>
</div>
15. Discus Built-in Helper Functions
● angular.isString: returns true if the object or value given is of the type string
○ Syntax: angular.isString(value1)
○ Examples
■ angular.isString("hello") // true
■ angular.isString([1, 2]) // false
■ angular.isString(42) // false
● angular.isArray: Returns true if is of the type Array.
○ Syntax: angular.isArray(value)
○ Examples
■ angular.isArray([]) // true
■ angular.isArray([2, 3]) // true
■ angular.isArray(17) // false
● angular.merge: takes all the enumerable properties from the source object to
deeply extend the destination object
○ Syntax: angular.isArray(value)
○ Examples
■ angular.merge({name: "king roland"}, {password: "12345"})
// {name: "king roland", password: "12345"}
■ angular.merge({a: 1}, [4, 5, 6]) // {0: 4, 1: 5, 2: 6, a: 1}
● angular.isDefined tests a value if it is defined
○ Syntax: angular.isDefined(someValue)
○ Examples
■ angular.isDefined(42) // true
■ angular.isDefined(undefined) // false
● angular.isUndefined tests a value if it is defined
○ Syntax: angular.isUndefined(someValue)
○ Examples
■ angular.isUndefined(42) // false
■ angular.isUndefined(undefined) // true
● angular.isDate returns true if object passed to it is of the type Date.
○ Syntax: angular.isDate(value)
○ Examples
■ angular.isDate("lone star") // false
■ angular.isDate(new Date()) // true
● angular.isNumber returns true if Number, this includes +Infinity, -Infinity and
NaN
○ Syntax: angular.isNumber(value)
○ Examples
■ angular.isNumber("23") // false
■ angular.isNumber(NaN) // true
■ angular.isNumber(Infinity) // true
● angular.isFunction, angular.toJson, angular.fromJson, isObject, forEach
○ angular.forEach([2, 4, 6, 8, 10], (value, key) => console.log(key))