Unit 2 1
Unit 2 1
What is JavaScript
Javascript is lightweight programming language it is most well-known as the scripting
language for webpage validation
Versions of javascript
JavaScript ES1,ES2,ES3(97-99)
Es5(2009)
Es6(2015)
The yearly editions of ES6 (2016,17,28)
Javascript popular fame works:
1.NodeJs: runtime environment built to execute java script outside of browser.
2.ReactJs: React is a fast ,scalable and re-usable frame-work for building interactive user
interface(UI)
3.AngularJS:Angular uses databinding , which automatically synchronizes data between the
data and the client
For Mobile Apps :
ReactNative, Jquery Mobile, Mobile AngularUI, NativeScript
For Desktop:
ElectronJS: this framework for developing apps for different desktop platforms like windows,
linux, macos…etc
For Machine learning
Tensorflow ,deeplearning.js ,Convnet.js
Javascript => “Synchronous single-thread language”
Objects in Javascript:
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create class to get the object. But,
we direct create objects.
object={property1:value1,property2:value2.....propertyN:valueN}
emp={id:102,name:"Shyam Kumar",salary:40000}
console.log(emp.id+" "+emp.name+" "+emp.salary);
Example of Object :
let student ={name:’abc’,age:29,dept:’cse’}
above variable is called object variables object comes with key/ value pair it means property
and value in above object {name,age,dept} are keys {‘abc’,29,’cse’} are values
now let’s see how to access the values from the object . for accessing the values from object
we need key value like below . I want to know the age from the student object
console.log(student.age)
o/p:29
Complex Object:
if object have another object we called as complex object . let’s see how to handle complex
object
let student ={name:’abc’,age:20,address:{D.no:2-245,landmark:”Gandhi
nagar”,city:”vizag”}}
Now our task is access the value of student city form the student object . below statement is
used to access the city from above value
Console.log(student.address.city)
Delete keyword :
delete keywork used for delete the object like below . now I want to delete then address
property from student object
delete student.address
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object
and has no methods or properties.
Data Types: Every Variable has a data type that tells what kind of data is being stored in a
variable. There are two types of data types in JavaScript namely Primitive data types and
Non-primitive data types.
Primitive data types: The predefined data types provided by JavaScript language are
known as primitive data types. Primitive data types are also known as in-built data types.
Non-primitive data types: The data types that are derived from primitive data types of the
JavaScript language are known as non-primitive data types. It is also known as derived data
types or reference data types.
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
2 Comparison Operators
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:
= Assign 10+10 = 20
Now access the array elements below example used to access the array elements:
let college =["AEC","ACET","ACOE"];
let depts = Array ("cse", "it", "AI/ML","DS");
console.log(college[0]);
console.log(depts.length);
output : AEC
4
Few functions which is are used frequently with arrays :
1. pop()
2. unshift()
3. shift()
4. every()
5. foreach()
6. filter ()
7. map()
8. reduce()
1.pop():-
it is used to remove the last inserted element
we take array variable called user:
user=[‘raju’,21,’cse’]
now above array have 3 elements name ,age,dept
user.pop()
o/p: =[‘raju’,21]
last inserted element are deleted
2.unshift():-
Unshift() is used to add elements at the first index of the array
user =["raju",20]
user.unshift("rama") ;console.log(user);
o/p:
[ 'rama', 'raju', 20 ]
3 . Shift(): use remove the first element in the array
4.every(): method tests whether all elements in the array pass . the test implemented by the
provided function . it return Boolean
Example:
Num=[2,3,4,5,6]
A=Num.every((e)=>(e%2===0))
But above statement return false . because all elements must be true then only it returns true
other wise it returns false .
5.Foreach():for each method calls a function for each element in array for each not executed
for empty values
Num=[1,2,3]
Num.foreach((n)=>{console.log(n);}
6.Filter : when you want to select a subset of multiple elements from an array
7.Map: when you want to transform elements in an array
8.reduce: when you want derive a single value from multiple elements in an array
Num=[2,3,4,6]
Result=num.filter(e=>e%2).map(e=>e*2).reduce((a,b)=>a*b)
Console.log(result);
Functions in javascript:
Java script function are defined with function keyword
You can use a function declaration or function expression
Function is used for re-use a particular block of code
How to implement fuction in javascript we using function key word
Function show()
{
Console.log(“Hello Aditya”);
}
Function return and passing:-
How your pass the value in to function and return a value from function
Below example understand how to pass the value and return the value from the function
Function sayhellotouser(user)
{
return ‘hello ${user}!!’;
}
let user =’abc’;
let str = sayhellotouser(user);
console.log(str);
o/p: hello abc !!
function expression:
let a = 8+9 => it is expression
above statement expression => evaluate => assigned
in java script function treat as a object
let add = function(num1,num2)
{
return num1+num2;
}
Above function behaviour assigned to add variable
Now we call the above function using variable
res = add(2,3)
console.log(res)
o/p: 5
Arrow function :
Arrow function is very important function in reactjs frame work .it is a anonymous function
Like lambda function in python
Arrow function allow us to write shorter function
Syntax:
let myarrowfunction =(a,b)=>a*b
example of arrow function :
arrow function with out return value :
a_f=()=> console.log("hello iam javascript");
a_f()
o/p: hello iam javascript
another example arrow function with return value :
let us check number is ever or not
a_f=(num)=>{if(num%2==0){ return true }
else {return false }
}
p=a_f(8)
console.log(p)
Why angular ?
Easy to work with: All you need to know to work with AngularJS is the basics of HTML,
CSS, and Javascript, not necessary to be an expert in these technologies.
Time-saving: AngularJs allows us to work with components and hence we can use them
again which saves time and unnecessary code.
Ready to use a template: AngularJs is mainly plain HTML, and it mainly makes use of
the plain HTML template and passes it to the DOM and then the AngularJS compiler. It
traverses the templates and then they are ready to use.
1.Model : This component consists of a database & is responsible for managing the data &
logic of the application. It responds to the request made by the View component & the
instruction given by the Controller component, in order to update itself.
2.View : This component is responsible for displaying the application data to the users. The
View is basically the user interface that helps to render the required data to the user, with
the help of the AngularJS expressions.
3.Controller: This component is responsible for communicating & interacting between the
Model & the View Component, i.e. its main job is to connect the model and the view
component. It helps to validate the input data by implementing some business logic that
manipulates the state of the data model.
Angular Js Expression:
Before expressions we need to understand Angular Js Directives
Angular Js Directives or ngModel Directives :
in angular we extend html with new attributes called Directives :
through this directives we add more functionality on html elements
Angular JS directive are extend html attributes with prefix ng-
$eval([expression], [locals]);
<script>
var app = angular.module('app', []);
app.controller("EvalController", function($scope) {
$scope.intA = 23;
$scope.intB = 54;
$scope.result = $scope.$eval('intA +intB');
});
</script>
ng-controller:
Angular Js applications are controlled by controllers. A controller is a java script object
created by a standard java script object constructor
The ng-controller directive adds a controller to your application. In the controller you can
write code, and make functions and variables, which will be parts of an object, available
inside the current HTML element. In AngularJS this object is called a scope.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp">
<div ng-controller="myCtrl">
Controller1: {{controller1}}
</div>
<div ng-controller="myctrl2">
Controller2 : {{ controller2 }}</div></div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.controller1 = "This is from controller1";
});
app.controller('myctrl2', function($scope) {
$scope.controller2=" This is from controller2 ";
});
</script>
<p>This example shows how to define a controller, and how to use variables made for the
scope.</p></body>
</html>
Note:
$scope:The scope is the binding part between the HTML (view) and the JavaScript
(controller).
The scope is available for both the view and the controller.
When you make a controller in AngularJS, you pass the $scope object as an argument:
Angular Js Form validation & Form Submission
AngularJS is constantly updating the state of both the form and the input fields.
They are all properties of the input field, and are either true or false.
They are all properties of the form, and are either true or false.
You can use these states to show meaningful messages to the user. Example, if a field is
required, and the user leaves it blank, you should give the user a warning:
Form Submission
Form submission is submit the input data to server using various html controls
input elements
select elements
button elements
textarea elements
Data-Binding
input elements:
The ng-model directive binds the input controller to the rest of your application.
<form>
</form>
</div>
<script>
app.controller('formCtrl', function($scope) {
});
</script>
acet
First Name:
Select elements
Select elements means radio button and selectbox or check box I go through radio button for
example
<form>
Pick a topic:
</form>
<div ng-switch="myVar">
<div ng-switch-when="dogs">
<h1>Dogs</h1>
</div>
<div ng-switch-when="tuts">
<h1>Tutorials</h1>
<div ng-switch-when="cars">
<h1>Cars</h1>
</div>
</div>
In above we use directives ng-switch and ng-switch-when this directives like switch case in
our regular programming language
Dogs
Button Element
Button element we can use same as javascript callback function with html
Below we implement controller. in controller we implement the reset() function using $scope
already we discussed about $scope
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.master = {College: "ACET", Dept:"CSE"};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
});
</script>
above code we have reset function now we call that function from html button element like
below
<button ng-click="reset()">RESET</button>
Textarea:
For textarea we have several directives below we find several directives which come with
textarea
<textarea
ng-model="string"
[name="string"]
[required="string"]
[ng-required="string"]
[ng-minlength="number"]
[ng-maxlength="number"]
[ng-change="string"]
>
...
</textarea>
Angular events :
AngularJS includes certain directives which can be used to provide custom behavior on
various DOM events, such as click, dblclick, mouseenter etc.
Generally an event is an action or occurrence recognized by software
In anularjs we several directives for mouse events , click events, key events … etc
Both Angular Event & the HTML Event will be executed & will not overwrite with an
HTML Event. It can be added using the Directives mentioned below:
ng-mousemove: The movement of the mouse leads to the execution of the event.
ng-mouseup: Movement of the mouse upwards leads to the execution of the event.
ng-mousedown: Movement of the mouse downwards leads to the execution of the
event.
ng-mouseenter: Click of the mouse button leads to the execution of the event.
ng-mouseover: Hovering the mouse leads to the execution of the event.
ng-keypress: Press of key leads to the execution of the event.
ng-keyup: Press of upward arrow key leads to the execution of the event.
ng-keydown: Press of downward arrow key leads to the execution of the event.
ng-click: Single click leads to the execution of the event.
ng-mouseleave: It is used to apply custom behavior when a mouse-leave event occurs
on a specific HTML element.
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body>
<p>
Move the mouse over increment
to increase the Total Count.
</p>
<div ng-app="App1"
ng-controller="Ctrl1">
<h1 ng-mousemove="count = count+1">
increment
</h1>
<h2>Total Count:</h2>
<h2>{{ count }}</h2>
</div>
<script>
var app = angular.module('App1', []);
app.controller('Ctrl1',function($scope) {
$scope.count=1;
})
</script>
</body>
</html>
Output:
AngularJs Application :
Already we know about directives ,forms ,validations and events . now we develop sample
angular applications
In these applications Add and remove the data in to list
1.Display the list from array
In the HTML, we use the ng-repeat directive to display a list using the items in the array.
<script>
CSE
ECE
EEE
Through above code display the departments list. using dept array. above code we ng-repeat
directive
In the HTML, add a text field, and bind it to the application with the ng-model directive.
In the controller, make a function named adddept, and use the value of the addMe input field
to add an item to the departments array.
Add a button, and give it an ng-click directive that will run the adddept function when the
button is clicked.
<script>
var app = angular.module("mydeptlist", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["CSE", "ECE", "EEE"];
$scope.adddept = function () {
$scope.products.push($scope.addMe);
}
});
</script>
In above code we used ng-click event for call the function adddept() from angularjs script
CSE
ECE
EEE
MECH
Add
In the controller, make a function named removedept, which takes the index of the item you
want to remove, as a parameter.
In the HTML, make a <span> element for each item, and give them an ng-click directive
which calls the removedept function with the current $index.
<script>
app.controller("myCtrl", function($scope) {
$scope.adddept = function () {
$scope.products.push($scope.addMe);
$scope.products.splice(x, 1);
});
</script>
<div ng-app="mydeptlist" ng-controller="myCtrl">
<ul>
</ul>
<input ng-model="addMe">
<button ng-click="adddept()">Add</button></div>