0% found this document useful (0 votes)
38 views23 pages

Unit 2 1

JavaScript is a lightweight programming language used for webpages. It has gone through multiple versions starting from ES1 through ES6 and beyond. JavaScript is commonly used to build interactive effects into webpages, and also has popular uses like Node.js, React, and Angular. It uses objects and has primitive data types like strings, numbers, and booleans.

Uploaded by

jokike8919
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views23 pages

Unit 2 1

JavaScript is a lightweight programming language used for webpages. It has gone through multiple versions starting from ES1 through ES6 and beyond. JavaScript is commonly used to build interactive effects into webpages, and also has popular uses like Node.js, React, and Angular. It uses objects and has primitive data types like strings, numbers, and booleans.

Uploaded by

jokike8919
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT-2

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 an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the object. But,
we direct create objects.

Creating object in javascript

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

Primitive Operations and expressions


Primitive Operations
Let see difference between let and var and const . this three key words are used for declaring
variables in javascript
Var Let Const
The scope of The scope of The scope of
a var variable is a let variable is a const variable is
functional scope. block scope. block scope.
It can be updated It can be updated It cannot be updated
and re-declared into but cannot be re- or re-declared into
the scope. declared into the the scope.
scope.
It can be declared It can be declared It cannot be
without without declared without
initialization. initialization. initialization.
It can be accessed t cannot be accessed It cannot be
without without accessed without
initialization as its initialization initialization, as it
default value is otherwise it will cannot be declared
“undefined”. give without
‘referenceError’. initialization.

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.

There are 7 primitive data types:


 string.
 number.
 bigint.
 boolean.
 undefined.
 symbol.
 null.
Operators in Javascript :
Javascript Operators perform the operations on operands for example
let sum=4+5
They are following types of operations in JavaScript
1.Arithmetic Operators
2.Comparision (Relational) Operators
3.Bitwise Operations
4.Logical Operations
5.Assignment Operations
6.Special Operations
1.Arithmetic Operations
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

2 Comparison Operators
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false


Examples on comparison:
In comparison we need observe few statements like
In javascript === (triple equal to place major role)
For example x=’3’ y=3
In case of == if x==y it returns true
In case of === if x===y it returns false
OPERATOR DATA TYPE

== CHECK NOT CHECK

=== CHECK CHECK

Above observation is important in javascript

3 Java script Bitwise Operator


The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2


4 Java Script Logical Operators :
The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

5 Java script Assignment Operators:


The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

6 Ternary Operator (?:)


Ternary Operator evaluates a condition and executes a block of code based on the condition
I want find given number is even or odd using ternary operator
Result = num%2==0 ? “EVEN”:”ODD”
Console.log(result);
Above statement is used ternary operator
Arrays in JavaScript
Array is a special variable, which can hold more than one value:
Creating Array and access the Elements from array . we have 2 ways to create the array
1. let college =[‘AEC’,’ACET’,’ACOE’];
2. let depts = Array (‘cse’, ’it’, ’AI/ML’,’DS’);

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)

What is Angular Js?


Angular Js is Javascript Open Source Front-end Frame work . that is mainly used to develop
single-page web Applications. This frame work maintained by google.
Key Points:
 AngularJS is a JavaScript framework that is mainly used for Frontend Development.
 It is used for making Single Page Applications(SPA).
 It is open source and is completely free for everyone.
 It uses the Model, View, Control(MVC) pattern for developing projects.

How to use angular java script use in our html page


For that you need import library from google
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
Through above library we can use anjularjs functionality in our html page

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.

MVC (Model View Controller):


Mvc is an architecture is a basically a software pattern used to develop a application
It consists of three components :
1. Model
2. View
3. Controller

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-

 The ng-app directive initializes an angular Application


 The ng-init directive initializes application data
 The ng-model directive binds the value of HTML Controls(input,select,textarea) to
application data
 The ng-repeat directive actually clones HTML elements once for each time in an
collection ng-repeat directive is used on an array of obect
Expressions in AngularJS are used to bind application data to HTML. The expressions are
resolved by AngularJS and the result is returned back to where the expression is written.
The expressions in AngularJS are written in double braces: {{ expression }}.
Sytnax: {{expression}}

Now we saw the Small example Program on Expression angularJS


In below example we add two number in html using anularJs
Expression
<!DOCTYPE html>
<html>
<body>
<script src=https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js>
</script>
<div ng-app="">
<p>Example Of Expression {{50 + 50 }} </p>
</div>
</body>
</html>
o/p: Now out put is Example Of Expression 100
if you remove the ng-app attribute in div tag
output will be display like Example Of Expression {{ 50 + 50 }}
Expression with Array
Expression can be used to work with arrays lets look at an example of angular js expression
with arrays :
<div ng-app=” “ ng-init=”marks=[5,6,7]” >
Subject :{{ marks[0] }}
</div>
Expression with Object:
Expression can be used to work with javascript object as well
Object in javascript
Let person = {Name:’ravi’,age:20}
<div ng-app=” “ ng-init=”person={Name:’ravi’ , age:20}”>
FirstName :{ { person.name} }
Age :{ {person.age} }
</div>
Expressions with String:
Expressions can be used with strings like below
<div ng-app=” “ ng-init=”firstname=’guru’;lastname=’99’ “ >
FirstName:{{ firstname }}
LastName:{{ lastname }}
</div>
Expression with $eval
The AngularJS $eval method is used to executes the AngularJS expression on the current
scope and returns the result. In AngularJS, expressions are similar to JavaScript code snippets
that are usually placed in bindings such as
{{ expression }}. AngularJS used internally $eval to resolve AngularJS expressions, such as
{{variable}}.
The important difference between $eval and $parse is that $eval is a scope method that
executes an expression on the current scope, while $parse is a globally available service.
The $eval method takes AngularJS expression and local variable object as parameter.
Syntax

$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 an object with the available properties and methods.

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

Angular js offers client-side form validation


Angular Js monitors the state of the form and input fields and notify the user about the
current state
Form State and Input State

AngularJS is constantly updating the state of both the form and the input fields.

Input fields have the following states:

 $untouched :The field has not been touched yet


 $touched : The field has been touched
 $invalid The field content is not valid
 $valid The field content is valid

They are all properties of the input field, and are either true or false.

Forms have the following states:

 $invalid The form content is not valid


 $valid The form content is valid
 $submitted The form is submitted

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:

Example for form validation in AngularJS:


<form name="myForm">
<p>Name:
<input name="myName" ng-model="myName" required>
<span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is
required.</span>
</p>
<p>Address:
<input name="myAddress" ng-model="myAddress" required>
</p>
</form>
o/p:-

Form Submission
Form submission is submit the input data to server using various html controls

Input controls are the HTML input elements:

 input elements
 select elements
 button elements
 textarea elements

Data-Binding

Input controls provides data-binding by using the ng-model directive.

input elements:

<input type="text" ng-model="firstname">

The application does now have a property named firstname.

The ng-model directive binds the input controller to the rest of your application.

The property firstname, can be referred to in a controller:

<div ng-app="myApp" ng-controller="formCtrl">

<form>

First Name: <input type="text" ng-model="firstname">

</form>

</div>
<script>

var app = angular.module('myApp', []);

app.controller('formCtrl', function($scope) {

$scope.firstname = "acet ";

});

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

<input type="radio" ng-model="myVar" value="dogs">Dogs

<input type="radio" ng-model="myVar" value="tuts">Tutorials

<input type="radio" ng-model="myVar" value="cars">Cars

</form>

<div ng-switch="myVar">

<div ng-switch-when="dogs">

<h1>Dogs</h1>

<p>Welcome to a world of dogs.</p>

</div>

<div ng-switch-when="tuts">

<h1>Tutorials</h1>

<p>Learn from examples.</p>


</div>

<div ng-switch-when="cars">

<h1>Cars</h1>

<p>Read about cars.</p>

</div>

</div>

In above we use directives ng-switch and ng-switch-when this directives like switch case in
our regular programming language

Pick a topic: Dogs Tutorials Cars

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

Start by making an application called Departments_List, and add a controller


named myCtrl to it.

The controller adds an array named depts to the current $scope.

In the HTML, we use the ng-repeat directive to display a list using the items in the array.

<script>

var app = angular.module("mydeptlist ", []);


app.controller("myCtrl", function($scope) {
$scope.depts = ["CSE", "ECE", "EEE"];
})</script>

<div ng-app="mydeptlist" ng-controller="myCtrl">


<ul>
<li ng-repeat="x in depts">{{x}}</li>
</ul>
</div>

 CSE
 ECE
 EEE

So far we have made an HTML list based on the items of an array.

Through above code display the departments list. using dept array. above code we ng-repeat
directive

The ng-repeat directive repeats a set of HTML, a given number of times.

The set of HTML will be repeated once per item in a collection.

The collection must be an array or an object.

2.Adding Elements into array through user elements

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>

<div ng-app=" mydeptlist" ng-controller="myCtrl">


<ul>
<li ng-repeat="x in depts">{{x}}</li>
</ul>
<input ng-model="addMe">
<button ng-click="adddept()">Add</button>
</div>

In above code we used ng-click event for call the function adddept() from angularjs script

Output for above code :

 CSE
 ECE
 EEE
 MECH

Add

Write in the input field to adddepts.

3.Delete the elements

We also want to be able to remove items from the department list.

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>

var app = angular.module("mydeptlist", []);

app.controller("myCtrl", function($scope) {

$scope.depts= ["CSE", "ECE", "EEE","MECH"];

$scope.adddept = function () {

$scope.products.push($scope.addMe);

$scope.removedept = function (x) {

$scope.products.splice(x, 1);

});

</script>
<div ng-app="mydeptlist" ng-controller="myCtrl">

<ul>

<li ng-repeat="x in depts">{{x}}<span ng-click="removedept($index)">×</span></li>

</ul>

<input ng-model="addMe">

<button ng-click="adddept()">Add</button></div>

Output of above code

Conclusion about angular js application : in this application development just we perform


stack like operations or curd operation . The operations are :add element , delete element
,show elements

You might also like