0% found this document useful (0 votes)
13 views88 pages

Unit II - WT

Unit II covers client-side technologies focusing on JavaScript and the Document Object Model (DOM). It includes an introduction to JavaScript, its features, applications, advantages, and disadvantages, along with a discussion on how to implement JavaScript in HTML. The unit also highlights the importance of JavaScript in web development, server applications, and various other domains such as game development and mobile applications.

Uploaded by

Sumit Kolgire
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)
13 views88 pages

Unit II - WT

Unit II covers client-side technologies focusing on JavaScript and the Document Object Model (DOM). It includes an introduction to JavaScript, its features, applications, advantages, and disadvantages, along with a discussion on how to implement JavaScript in HTML. The unit also highlights the importance of JavaScript in web development, server applications, and various other domains such as game development and mobile applications.

Uploaded by

Sumit Kolgire
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/ 88

Unit II

Client Side Technologies:

JavaScript and DOM

Contents of Unit II
JavaScript: Introduction to JavaScript, JavaScript in
perspective, basic syntax, variables and data types,
statements, operators, literals, functions, objects, arrays,
built in objects, JavaScript debuggers.
DOM: Introduction to Document Object Model, DOM
history and levels, intrinsic event handling, modifying
element style, the document tree, DOM event handling,
jQuery, Overview of Angular JS.

1
Introduction to JavaScript
1. JavaScript is a lightweight, cross-platform, single-
threaded, and interpreted compiled programming
language which is also known as the scripting
language for webpages.
2. It is well-known for the development of web pages,
and many non-browser environments also use it.
3. JavaScript is a weakly typed language (dynamically
typed).
3

• JavaScript can be used for Client-side


developments as well as Server-side
developments.
• JavaScript is both an imperative and declarative
type of language.
• JavaScript contains a standard library of objects,
like Array, Date, Math, and a core set of language
elements like operators, control structures, and
statements.

2
Java Script

Client Side front-end


Scripting scripting
Language language

Dynamic
5

Client-side:
It supplies objects to control a browser and its Document

Object Model (DOM). Like if client-side extensions allow

an application to place elements on an HTML form and

respond to user events such as mouse clicks, form input

and page navigation.

Useful libraries for the client side are AngularJS, ReactJS,

VueJS, and so many others.


6

3
Server-side:
• It supplies objects relevant to running JavaScript on a
server. For if the server-side extensions allow an
application to communicate with a database, and
provide continuity of information from one invocation
to another of the application or perform file
manipulations on a server.
• The useful framework which is the most famous these
days is node.js.
7

Imperative language –
• In imperative programming, your code is based on
statements that change the program state by telling
the computer how to do things.
• In other words, your code is based on defining
variables and changing the values of those variables.
• It simply controls the flow of computation.

4
Declarative programming –
In declarative programming, your code is based
on expressions that evaluate their result based
on their input by telling the computer what you
want.

Statements versus Expressions


• Imperative code uses statements and declarative
code uses expressions.

• Expressions evaluate to a value while statements tell


the computer to do something.

10

5
JavaScript can be added to your HTML file in two ways:
Internal JS: We can add JavaScript directly to our HTML
file by writing the code inside the <script> tag. The
<script> tag can either be placed inside the <head> or the
<body> tag according to the requirement.

External JS: We can write JavaScript code in another files


having an extension.js and then link this file inside the
<head> tag of the HTML file in which we want to add this
code.
11

Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Basic Example to Describe JavaScript
</title>
</head>
<body>
<!-- JavaScript code can be embedded inside
head section or body section -->
<script>
console.log("Welcome to JavaScript World");
</script>
</body>
</html>

Output: The output will display on the console. Welcome to

JavaScript World

12

6
History of JavaScript:
• It was created in 1995 by Brendan Eich while he was an
engineer at Netscape.
• It was originally going to be named LiveScript but was renamed.
• Unlike most programming languages, JavaScript language has no
concept of input or output.
• It is designed to run as a scripting language in a host
environment, and it is up to the host environment to provide
mechanisms for communicating with the outside world.
• The most common host environment is the browser.

13

Features of JavaScript:
• JavaScript is the most popular language on earth.
• With advances in browser technology and JavaScript
having moved into the server with Node.js and other
frameworks, JavaScript is capable of so much more.
Here are a few things that we can do with JavaScript:
• JavaScript was created in the first place for DOM
manipulation. Earlier websites were mostly static, after
JS was created dynamic Web sites were made.
14

7
• Functions in JS are objects. They may have properties
and methods just like other objects. They can be
passed as arguments in other functions.
• Can handle date and time.
• Performs Form Validation although the forms are
created using HTML.
• No compiler is needed.

15

Applications of JavaScript:
Web Development: Adding interactivity and behavior to static sites
JavaScript was invented to do this in 1995. By using AngularJS that can be
achieved so easily.
Web Applications: With technology, browsers have improved to the extent
that a language was required to create robust web applications. When we
explore a map in Google Maps then we only need to click and drag the
mouse. All detailed view is just a click away, and this is possible only
because of JavaScript. It uses Application Programming Interfaces(APIs)
that provide extra power to the code. The Electron and React are helpful in
this department.
Server Applications: With the help of Node.js, JavaScript made its way
from client to server and Node.js is the most powerful on the server side.
16

8
Games: Not only in websites, but JavaScript also helps in creating games for

leisure. The combination of JavaScript and HTML 5 makes JavaScript

popular in game development as well. It provides the EaseJS library which

provides solutions for working with rich graphics.

Smartwatches: JavaScript is being used in all possible devices and

applications. It provides a library PebbleJS which is used in smartwatch

applications. This framework works for applications that require the

Internet for their functioning.

Art: Artists and designers can create whatever they want using JavaScript

to draw on HTML 5 canvas, and make the sound more effective also can be

used p5.js library.

17

• Machine Learning: This JavaScript ml5.js library can be used in web


development by using machine learning.
• Mobile Applications: JavaScript can also be used to build an
application for non-web contexts. The features and uses of
JavaScript make it a powerful tool for creating mobile applications.
This is a Framework for building web and mobile apps using
JavaScript. Using React Native, we can build mobile applications for
different operating systems. We do not require to write code for
different systems. Write once use it anywhere!

18

9
JavaScript Advantages
Changing an image
Implementing
on moving mouse over
form validation
it

Performing complex
React to user actions, calculations

Content loading and Sections of a page


changing dynamically appearing and
disappearing

19

JavaScript Advantages
Simple − JavaScript is simple to comprehend and pick up. Both users and

developers will find the structure to be straightforward. Additionally, it is very

doable to implement, saving web developers a tonne of money when creating

dynamic content.

Speed − JavaScript is a "interpreted" language, it cuts down on the time needed

for compilation in other programming languages like Java. Another client-side

script is JavaScript, which accelerates programme execution by eliminating the

wait time for server connections.

No matter where JavaScript is hosted, it is always run in a client environment to

reduce bandwidth usage and speed up execution.


20

10
JavaScript Advantages
Server Load − Data validation can be done within the browser itself
rather than being forwarded to the server because JavaScript is client-
side. The entire website does not need to be reloaded in the event of
any discrepancy. Only the chosen area of the page is updated by the
browser.
Interoperability − Because JavaScript seamlessly integrates with other
programming languages, many developers favour using it to create a
variety of applications. Any webpage or the script of another
programming language can contain it.

21

JavaScript Disadvantages
Cannot Debug − Although some HTML editors allow for
debugging, they are not as effective as editors for C or C++.
Additionally, the developer has a difficult time figuring out the
issue because the browser doesn't display any errors.
Unexpected stop of rendering − The website's entire
JavaScript code can stop rendering due to a single error in the
code. It appears to the user as though JavaScript is absent.
The browsers, however, are very forgiving of these mistakes.

22

11
JavaScript Disadvantages
Client-side Security − The user can see the JavaScript code; it could be misused by
others. These actions might involve using the source code anonymously. Additionally,
it is very simple to insert code into the website that impair the security of data
transmitted via the website.
Inheritance − JavaScript does not support multiple inheritance; only one inheritance is
supported. This property of object-oriented languages might be necessary for some
programs.
Browser Support − Depending on the browser, JavaScript is interpreted differently.
Therefore, before publication, the code needs to run on various platforms. We also
need to check the older browsers because some new functions are not supported by
them.

23

Limitations of JavaScript:
Security risks:
JavaScript can be used to fetch data using AJAX or by manipulating tags that
load data such as <img>, <object>, <script>. These attacks are called cross-site
script attacks. They inject JS that is not part of the site into the visitor’s
browser thus fetching the details.

Performance:
JavaScript does not provide the same level of performance as offered by
many traditional languages as a complex program written in JavaScript would
be comparatively slow. But as JavaScript is used to perform simple tasks in a
browser, so performance is not considered a big restriction in its use.

24

12
Complexity:
To master a scripting language, programmers must have a
thorough knowledge of all the programming concepts, core
language objects, and client and server-side objects otherwise it
would be difficult for them to write advanced scripts using
JavaScript.
Weak error handling and type checking facilities:
It is a weakly typed language as there is no need to specify the
data type of the variable. So wrong type checking is not
performed by compile.
25

What Can JavaScript Do?

• Can validate form • Can read and write


data HTML elements

• Can access / modify


• Can handle events
browser cookies

26

13
What JavaScript Can’t Do?

• Can not do • Can not close a


database related window that it
operation hasn't opened.

Cannot Read From Cannot Protect


or Write to Files Your Page Source
in the Client. or Images

Basic Syntax
<script>
// JavaScript Code
</script>
The script tag takes two important attributes −
Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML
(and XHTML, its successor) have phased out the use of this attribute.
Type − This attribute is what is now recommended to indicate the
scripting language in use and its value should be set to "text/javascript".

<script language = "javascript" type = "text/javascript">


JavaScript code </script>

28

14
Your First JavaScript Code
<html>
<body>
<script language = "javascript" type = "text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
This code will produce the following result −
Hello World!

29

JavaScript - Placement in HTML File


Script in Script in
<head>...</head> <body>...</body>
section section

Script in External file and


Script in
then include
<head> and
link in HTML file head
<body> section
section

30

15
Syntax of Javascript
Write JavaScript code inside HTML
Head Tag, Body Tag or External File

Use <Script> tag inside Head, body tag

Example:
<script >
JavaScript code
</script>

31

Java Script Example- 1


Print Hello Message
<html> Script Code in
<body> HTML
<script> file in Body Tag
document.write("Hello World")
</script>
</body>
</html>

32

16
Java Script Example- 2
Print Hello Message
<html>
Script Code in HTML
<head>
file in Head Tag
<script>
document.write("Hello World")
</script>
</head>
</html>

33

Java Script Example- 3


Print Hello Message
<html>
Print Message
<head>
using alert
<script>
alert("Hello World")
</script>
</head>
</html>

34

17
Java Script Example- 4 Print Hello
Message
<html>
<head>
<script> Print Message after
function sayHello() clicking button
{
alert("Hello World")
}
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

35

Variables and Data Types


Variables in JavaScript
Variables are Containers for Storing Data
JavaScript Variables can be declared in 4 ways:
1. var
2. let
3. Const
4. Automatically / Using Nothing

36

18
• Example using var
var x = 5;
var y = 6;
var z = x + y;

• Example using let


let x = 5;
let y = 6;
let z = x + y;

• Example using const


const x = 5;
const y = 6;
const z = x + y; 37

Java Script Variables


• Always declare JavaScript variables with var,let, or
const.
• The var keyword is used in all JavaScript code from
1995 to 2015.
• The let and const keywords were added to JavaScript
in 2015.
• If you want your code to run in older browser, you
must use var
38

19
• When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed
(Arrays and Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers.

39

JavaScript Identifiers
• All JavaScript variables must be identified with

unique names.

• These unique names are called identifiers.

• JavaScript identifiers are case-sensitive.

• Identifiers can be short names (like x and y) or

more descriptive names (age, sum, totalVolume).

40

20
The general rules for constructing names for variables
(unique identifiers) are:

Names can contain letters, digits, underscores, and dollar


signs.
Names must begin with a letter.
Names can also begin with $ (dollar) and _ (underscrore) .
Names are case sensitive (y and Y are different variables).
Reserved words (like JavaScript keywords) cannot be used as
names.

41

Re-Declaring JavaScript Variables


• If you re-declare a JavaScript variable declared with var, it will
not lose its value.
• You cannot re-declare a variable declared with let or const.
• The variable carName will still have the value "Volvo" after
the execution of these statements:
Example
var carName = "Volvo";
var carName;

42

21
JavaScript Arithmetic
• As with algebra, you can do arithmetic with JavaScript
variables, using operators like = and +:
Example
let x = 5 + 2 + 3;
• You can also add strings, but strings will be
concatenated:
Example
let x = "John" + " " + "Doe";
• If you put a number in quotes, the rest of the numbers
will be treated as strings, and concatenated.
Example
• let x = 2 + 3 + "5";
43

JavaScript Dollar Sign $


• Since JavaScript treats a dollar sign as a letter,
identifiers containing $ are valid variable names:

Example
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;

44

22
JavaScript Underscore (_)
• Since JavaScript treats underscore as a letter,
identifiers containing _ are valid variable names:

Example
let _lastName = "Johnson";
let _x = 2;
let _100 = 5;

45

JavaScript Data Types


• JavaScript has 8 Datatypes
String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object

• The Object Datatype


The object data type can contain:
An object
An array
A date 46

23
JavaScript Strings
A string (or a text string) is a series of characters like "John
Doe".
Strings are written with quotes.
You can use single or double quotes:
Example
// Using double quotes:
let carName1 = "Volvo XC60";

// Using single quotes:


let carName2 = 'Volvo XC60';
47

JavaScript Numbers
All JavaScript numbers are stored as decimal numbers
(floating point).
Numbers can be written with, or without decimals:

Example
// With decimals:
let x1 = 34.00;
// Without decimals:
let x2 = 34;

48

24
Exponential Notation
• Extra large or extra small numbers can be written
with scientific (exponential) notation:
Example
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123

49

JavaScript BigInt
• All JavaScript numbers are stored in a a 64-bit
floating-point format.
• JavaScript BigInt is a new datatype (ES2020)
that can be used to store integer values that
are too big to be represented by a normal
JavaScript Number.
Example
let x = BigInt("123456789012345678901234567890");

25
JavaScript Booleans
Booleans can only have two values: true or false.

Example :
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false

51

JavaScript Arrays
• JavaScript arrays are written with square brackets.
• Array items are separated by commas.
• The following code declares (creates) an array called
cars, containing three items (car names):
Example
const cars = ["Saab", "Volvo", "BMW"];

52

26
JavaScript Objects
• JavaScript objects are written with curly braces {}.
• Object properties are written as name:value pairs,
separated by commas.
Example :
const person = {firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"};

53

The typeof Operator


You can use the JavaScript typeof operator to find the type of a JavaScript variable.
The typeof operator returns the type of a variable or an expression:

Example
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string“
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"
54

27
Undefined
In JavaScript, a variable without a value, has the value
undefined. The type is also undefined.
Example
let car; // Value is undefined
Any variable can be emptied, by setting the value to
undefined. The type will also be undefined.
car = undefined; // Value is undefined, type is
undefined

Empty Values
An empty value has nothing to do with
undefined.
An empty string has both a legal value and a
type.
Example
let car = ""; // The value is "", the typeof is
"string"

56

28
Statements
• The programming instructions written in a program in
a programming language are known as statements.
• A JavaScript program is a list of programming
statements.
• In HTML, JavaScript programs are executed by the web
browser.
• The statements are executed, one by one, in the same
order as they are written.
57

• JavaScript statements are composed of:


Values, Operators, Expressions, Keywords,
and Comments.
This statement tells the browser to write "Hello
Dolly." inside an HTML element with id="demo":

Example
document.getElementById("demo").innerHTM
L = "Hello Dolly.";

29
Semicolons ;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:

Examples
let a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
When separated by semicolons, multiple statements on one
line are allowed:
a = 5; b = 6; c = a + b;

59

JavaScript White Space


• JavaScript ignores multiple spaces.
• You can add white space to your script to make it more
readable.
The following lines are equivalent:
let person = "Hege";
let person="Hege";
A good practice is to put spaces around operators ( = + - *
/ ):
let x = y + z;

30
JavaScript Line Length and Line Breaks
• Javascript code preferred line length by most
programmers is upto 80 characters.
• If a JavaScript statement does not fit on one line, the
best place to break it is after an operator.
Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";

61

JavaScript Code Blocks


• JavaScript statements can be grouped together in

code blocks, inside curly brackets {...}.


• The purpose of code blocks is to define statements
to be executed together.
Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}

62

31
JavaScript Keywords
• Keywords are reserved words and cannot be used as variable
name.
• A Javascript keyword tells about what kind of operation it will
perform.
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition

switch Marks a block of statements to be executed in different cases

for Marks a block of statements to be executed in a loop


function Declares a function
return Exits a function
try Implements error handling to a block of statements
63

JavaScript Operators

• The Addition Operator + adds numbers:


• The Assignment Operator = assigns a value to a variable.

64

32
JavaScript Assignment
JavaScript Assignment
The Assignment Operator (=) assigns a value to a variable:

Assignment Examples
let x = 10;

JavaScript Addition
The Addition Operator (+) adds numbers:

Adding
let x = 5;
let y = 2;
let z = x + y;

JavaScript Multiplication
The Multiplication Operator (*) multiplies numbers:

Multiplying
let x = 5;
let y = 2;
let z = x * y;

65

Types of JavaScript Operators


There are different types of JavaScript operators:

• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• String Operators
• Logical Operators
• Bitwise Operators
• Ternary Operators
• Type Operators
66

33
JavaScript Arithmetic Operators
Arithmetic Operators are used to perform arithmetic on
numbers:
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
67

JavaScript Assignment Operators


Assignment operators assign values to JavaScript variables.
The Addition Assignment Operator (+=) adds a value to a
variable.

Operator Example Same As


= x=y x=y
+= x += y x=x+y
-= x -= y x=x-yx
*= x *= y =x*yx
/= x /= y =x/yx
%= x %= y =x%y
**= x **= y x = x ** y

34
JavaScript Comparison Operators

Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
69

JavaScript String Comparison


• All the comparison operators above can also be used on strings:
Example
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
Note that strings are compared alphabetically.

JavaScript String Addition


The + can also be used to add (concatenate) strings:
Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
70

35
The += assignment operator can also be used to add (concatenate) strings:
Example
let text1 = "What a very ";
text1 += "nice day";
The result of text1 will be:
What a very nice day
Adding Strings and Numbers
Adding two numbers, will return the sum, but adding a number and a string
will return a string:
Example
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
The result of x, y, and z will be:
10
55
Hello5 71

JavaScript Logical Operators


Operator Description
&& logical and
|| logical or
! logical not

JavaScript Type Operators


Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an
instance of an object type

72

36
JavaScript Bitwise Operators
Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit
number. The result is converted back to a JavaScript number.
Operator Description Example Same as Result Decimal
& AND 5&1 0101 & 0001 0001 1
| OR 5|1 0101 | 0001 0101 5
~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0001 0100 4
<< left shift 5 << 1 0101 << 1 1010 10
>> right shift 5 >> 1 0101 >> 1 0010 2
>>> unsigned right shift 5 >>> 1 0101 >>> 1 0010 2

Literals
JavaScript Literals are the fixed value that
cannot be changed,
you do not need to specify any type of
keyword to write literals.
Literals are often used to initialize variables in
programming

74

37
JavaScript supports various types of literals
which are listed below:
Numeric(Integer) Literal
Floating-Point Literal
Boolean Literal
String Literal
Array Literal
Regular Expression Literal
Object Literal

75

Integer Literals
• It can be expressed in the decimal(base 10),
hexadecimal(base 16) or octal(base 8) format.
• Decimal numeric literals consist of a sequence of digits
(0-9) without a leading 0(zero).
• Hexadecimal numeric literals include digits(0-9), letters
(a-f) or (A-F).
• Octal numeric literals include digits (0-7). A leading
0(zero) in a numeric literal indicates octal format.
120 // decimal literal
021434 // octal literal
0x4567 // hexadecimal literal
76

38
2. Floating Number Literals
It contains a decimal point(.)
A fraction is a floating-point literal
It may contain an Exponent.

6.99689 // floating-point literal


-167.39894 // negative floating-point
literal

77

3. String Literals
A string literal is a combination of zero or
more characters enclosed within a single(') or
double quotation marks (").
"Study" // String literal
'tonight' // String literal

78

39
4. Boolean Literals
Boolean literal supports two values only either
true or false.

true // Boolean literal


false // Boolean literal

79

4. Array Literals
• An array literal is a list of zero or more expressions
representing array elements that are enclosed in a
square bracket([]).
• Whenever you create an array using an array literal,
it is initialized with the elements specified in the
square bracket.
var emp = ["aman","anu","charita"]; // Array literal

80

40
6. Object Literals
• It is a collection of key-value pairs enclosed in curly
braces({}).
• The key-value pair is separated by a comma.

• Examples of an object literal with a declaration are


var userObject = { },
var student = { f-name : “John”, l-name : “D”, “rno”:
23, “marks”: 60}

7. Regular Expression Literal


Regular Expression is a pattern, used to match
a character or string in some text.
It is created by enclosing the regular
expression string between forward slashes.
var r1 = /ab+c/; // Regular Expression literal
var r2 = new RegExp("abc"); // Regular
Expression literal
82

41
FUNCTIONS

Anonymous Function
Named Function
Function with return statement

83

Anonymous Function
<script>
var showMessage = function (){
alert("Hello World!");
};
showMessage();
</script>

84

42
Named Function without argument

function SayHello() {
alert("Hello ");
}
SayHello();

85

Named Function with argument


function SayHello(firstName)
{
alert("Hello " + firstName);
}
SayHello(“Gajanan");

86

43
Function with return statement
function sum(val1, val2)
{
return val1 + val2;
};
var result = sum(10,20);

87

A JavaScript function is a block of code designed to perform


a particular task.
A JavaScript function is executed when "something" invokes
it (calls it).
A JavaScript function is defined with the function keyword,
followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores,
and dollar signs (same rules as variables).
The code to be executed, by the function, is placed inside
curly brackets: {}
88

44
Objects
• Objects are variables too. But objects can contain
many values.
const car = {type:"Fiat", model:"500", color:"white"};
• The values are written as name:value pairs (name
and value separated by a colon).
• It is a common practice to declare objects with the
const keyword.

89

Object Definition
You define (and create) a JavaScript object with an object literal:
Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Spaces and line breaks are not important. An object definition can span
multiple lines:
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

90

45
Object Properties
The name:values pairs in JavaScript objects are called
properties:

Property Property Value


firstName John
lastName Doe
age 50
eyeColor blue

91

Accessing Object Properties


You can access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]

Examples :
Example1
person.lastName;
Example2
person["lastName"];
92

46
Arrays
• An array is a special variable, which can hold more than one value:
const cars = ["Saab", "Volvo", "BMW"];
Why Use Arrays?
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the
values by referring to an index number.

Creating an Array
• Using an array literal is the easiest way to create a JavaScript Array.
• It is a common practice to declare arrays with the const keyword.
Syntax:
const array_name = [item1, item2, ...];
Example :
const cars = ["Saab", "Volvo", "BMW"];

• Spaces and line breaks are not important. A declaration can span
multiple lines:
Example
const cars = [
"Saab",
"Volvo",
"BMW"
];

47
Built in Objects
• Built-in objects, also known as global objects, are
objects that are readily available in JavaScript
without the need for explicit instantiation.
• They provide a range of functionalities and can be
used directly in your code.
• some commonly used built-in objects in
JavaScript:
95

Object: The base object in JavaScript, from


which all other objects inherit. It is used to
create key-value pairs and represents various
entities in the program.
const person = {
name: "John",
age: 30
};
Array: Used to store and manipulate lists of
items.
const numbers = [1, 2, 3, 4, 5];

48
String: Used for manipulating and working with textual
data.
const message = "Hello, World!";
Number: Represents numeric data and provides
various utility methods for mathematical operations.
const pi = 3.14159;
Boolean: Represents a boolean value (true or false).
const isActive = true;

97

Function: Represents a JavaScript function.


function greet(name) {
return `Hello, ${name}!`;
}

Date: Used for working with dates and times.


const currentDate = new Date();

RegExp: Represents regular expressions for pattern matching


and manipulation of strings.
const pattern = /[a-zA-Z]+/;

Math: Provides mathematical constants and functions.


const squareRoot = Math.sqrt(25);
98

49
JSON: Provides methods for working with JSON (JavaScript Object
Notation) data.
const jsonData = '{"name": "Alice", "age": 25}';
const parsedData = JSON.parse(jsonData);

Promise: Represents a value that might be available now, or in the


future, or never.
const fetchData = new Promise((resolve, reject) => {
// Asynchronous operation
// Call resolve(data) when successful, or reject(error) on failure
});

Map: Represents a collection of key-value pairs where keys can be of


any type
const myMap = new Map();
myMap.set("name", "Bob");
myMap.set("age", 28);

Set: Represents a collection of unique values.


const mySet = new Set([1, 2, 3, 4, 4, 5]);

Error: Represents an error object that contains


information about runtime errors.
try {
// Something that might throw an error
} catch (error) {
console.error(error.message);
}
100

50
JavaScript Debuggers
The debugger keyword stops the execution of JavaScript,
and calls (if available) the debugging function.
This has the same function as setting a breakpoint in the
debugger.
If no debugging is available, the debugger statement has
no effect.
With the debugger turned on, this code will stop
executing before it executes the third line.
101

JavaScript Debuggers
All modern browsers have a built-in JavaScript debugger.
Built-in debuggers can be turned on and off, forcing
errors to be reported to the user.
With a debugger, you can also set breakpoints (places
where code execution can be stopped), and
examine variables while the code is executing.
You activate debugging in your browser with the F12 key,
and select "Console" in the debugger
menu.
102

51
Major Browsers' Debugging Tools
Normally, you activate Firefox
debugging in your browser with Open the browser.
F12, and select "Console" in the From the menu, select "Web
debugger menu.
Otherwise follow these steps: Developer".
Chrome Finally, select "Web Console".
Open the browser. Edge
From the menu, select "More Open the browser.
tools". From the menu, select
From tools, choose "Developer "Developer Tools".
tools". Finally, select "Console".
Finally, select Console. When the new option
"Develop" appears in the menu:
Choose "Show Error Console".

52
DOM: Introduction to Document
Object Model
The Document Object Model (DOM) is a programming
interface for HTML(HyperText Markup Language) and
XML(Extensible markup language) documents.
It defines the logical structure of documents and the way
a document is accessed and manipulated.
DOM is a way to represent the webpage in a structured
hierarchical way so that it will become easier for
programmers and users to glide through the document.
105

DOM: Document Object Model


• JavaScript can access all the elements in a
webpage making use of Document Object Model
(DOM).
• The web browser creates a DOM of the webpage
when the page is loaded.
• The DOM defines a standard for accessing
documents
• The DOM model is created as a tree of objects
106

53
DOM- Uses
With the object model, JavaScript gets all the power it
needs to create dynamic HTML:
1. JavaScript can change all the HTML elements in the page
2. JavaScript can change all the HTML attributes in the page
3. JavaScript can change all the CSS styles in the page
4. JavaScript can remove existing HTML elements and
attributes
5. JavaScript can add new HTML elements and attributes

107

Why DOM is required?


• When an HTML file is loaded into the browser, the javascript
can not understand the HTML document directly.
• So, a corresponding document is created(DOM).
• DOM is basically the representation of the same HTML
document but in a different format with the use of objects.
• Javascript interprets DOM easily i.e javascript can not
understand the tags(<h1>H</h1>) in HTML document but can
understand object h1 in DOM.
• Now, Javascript can access each of the objects (h1, p, etc) by
using different functions.
108

54
Structure of DOM:
• DOM can be thought of as a Tree or Forest(more than one tree).
• The term structure model is sometimes used to describe the tree-
like representation of a document.
• Each branch of the tree ends in a node, and each node contains
objects.
• Event listeners can be added to nodes and triggered on an
occurrence of a given event.
• One important property of DOM structure models is structural
isomorphism: if any two DOM implementations are used to create a
representation of the same document, they will create the same
structure model, with precisely the same objects and relationships.
109

Tree Structure

110

55
Example
• <html>
• <head>
• <title> My Text </title>
• </head>
• <body>
• <h1> My Header </h1>
• <p> My Paragraph </p>
• </body>
• </html>

111

DOM Levels

112

56
DOM- Properties & Methods
Methods Description

getElementById(id) Find an element by element id

getElementsByTagName(name) Find an element by Tag Name

getElementsByClassName(name) Find an element by Class Name

getElementsByName(name) Find an element by element


name

write() Writes new text to a document

113

Methods Example

.innerHTML document.getElementById(“demo”).inner
HTML

..Value document.getElementById(“t1”).Value

114

57
Example getElementById
<html>
<head><script>
function f1() {
var a= document.getElementById("t1").value;
alert(a); }
</script></head>
<body>
<input type="text" id="t1" >
<input type=button value="click" onclick="f1()">
</body>
</html>

Examples: getElementsByTagName
<html>
<head><script>
function f1() {
document.getElementsByTagName("p")[0].innerHTML="HT
ML"; }
</script></head>
<body>
<p> Hello</p>
<p > How Are You </p>
<input type=button value="click" onclick="f1()">
</body>
</html>

58
Example to calculate length
<script>
function f1() {
alert(document.getElementsByTagName("p").leng
th); }
</script><body>
<p> Hello</p>
<p class= “a1”> How Are You </p>
<h1 class= “a1”>Good Day </h1>
<input type=button value="click" onclick="f1()">
</body>
117

Examples: To change CSS Property


<html>
<head><script>
function f1() {
document.getElementsByClassName("a1")[1].style.color="re
d"; }
</script></head>
<body>
<p> Hello</p>
<p class= “a1”> How Are You </p>
<h1 class= “a1”>Good Day </h1>
<input type=button value="click" onclick="f1()">
</body>
</html>
118

59
Examples:To Disable/Enable element
<script>
function f1() {
document.getElementsById("t1").disabled= true; }
</script>
<body>
<input type="text" id="t1" >
<input type=button value="click" onclick="f1()">
</body>

119

Why called an Object Model?

• Documents are modeled using objects, and the model


includes not only the structure of a document but also
the behavior of a document and the objects of which
it is composed like tag elements with attributes in
HTML.

120

60
Properties of DOM:
• Let’s see the properties of the document object that can be
accessed and modified by the document object.

121

Window Object:
Window Object is object of the browser which is always at top of the

hierarchy.

It is like an API that is used to set and access all the properties and

methods of the browser.

It is automatically created by the browser.

Document object:
When an HTML document is loaded into a window, it becomes a

document object.

122

61
Document object: (Cont..)
The ‘document’ object has various properties that refer to other objects
which allow access to and modification of the content of the web page.

If there is a need to access any element in an HTML page, we always start


with accessing the ‘document’ object.

Document object is property of window object.

Form Object: It is represented by form tags.

Link Object: It is represented by link tags.

Anchor Object: It is represented by a href tags.

Form Control Elements:: Form can have many control elements such as text
fields, buttons, radio buttons, checkboxes, etc.

123

Example: In this example, We use HTML element id to find the DOM


HTML element.
<!DOCTYPE html>
<html>
<body>
<h2>Title Here</h2>
<!-- Finding the HTML Elements by their Id in DOM -->
<p id="intro">A Computer Science portal for geeks.</p>
<p>This example illustrates the <b>getElementById</b>
method.</p>
<p id="demo"></p>
<script>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML =
“My introduction is: " + element.innerHTML;
</script>
</body>
</html>

62
What DOM is not?
• The Document Object Model is not a binary description where it
does not define any binary source code in its interfaces.
• The Document Object Model is not used to describe objects in XML
or HTML whereas the DOM describes XML and HTML documents as
objects.
• The Document Object Model is not represented by a set of data
structures; it is an interface that specifies object representation.
• The Document Object Model does not show the criticality of objects
in documents i.e it doesn’t have information about which object in
the document is appropriate to the context and which is
not.
125

Example: This example illustrates the dom-


manipulation using getElementById() Method.
<!DOCTYPE html>
<html>
<head>
<title>DOM manipulation</title>
</head>
<body>
<label>Enter Value 1: </label>
<input type="text" id="val1" />
<br />
<br />
<label>Enter Value 2: </label>
<input type=".text" id="val2" />
<br />
<button onclick="getAdd()">Click To Add</button>
<p id="result"></p>
<script type="text/javascript">
function getAdd() {
// Fetch the value of input with id val1
const num1 =
Number(document.getElementById("val1").value);
126

63
// Fetch the value of input with id val2
const num2 =
Number(document.getElementById("val2").value);
const add = num1 + num2;
console.log(add);
// Displays the result in paragraph using dom
document.getElementById("result").innerHTML =
"Addition : " + add;

// Changes the color of paragraph tag with red


document.getElementById("result").style.color = "red";
}
</script>
</body>
</html>

OUTPUT :

127

Intrinsic Event Handling


• onclick attribute:
event occurs when a pointing device button is
clicked over an element

• ondblclick attribute:
occurs when a pointing device button is double
clicked over an element

• onmouseover attribute:
event occurs when a mouse is moved onto an
element

128

64
• onmousedown attribute:
event occurs when a mouse button is pressed over an element

• onmouseup attribute:
event occurs when a mouse button is released over an element

• onmouseout attribute:
event occurs when a mouse is moved away from an element

• onmousemove attribute:
event occurs when a mouse is moved while it is over an element

129

• onkeydown attribute:
event occurs when a key is pressed down over an
element

• onkeyup attribute:
event occurs when a key is released over an
element

• onkeypress attribute:
event occurs when a key is pressed and released
over an element

130

65
Modifying Element style
• Modifying an element's style using JavaScript is a common
task in web development.
• You can use JavaScript to dynamically change the appearance
of HTML elements by manipulating their CSS properties.
Here's how you can do it:
Using the ‘style’ Property:
• You can directly access and modify an element's inline style
using the style property.
• This method is suitable for making simple style changes.
131

// Get a reference to the element


const myElement = document.getElementById("myElement");

// Modify the element's background color


myElement.style.backgroundColor = "blue";

// Change the font size and color


myElement.style.fontSize = "16px";
myElement.style.color = "white";

132

66
Adding or Removing CSS Classes:
• For more complex styling changes or to apply predefined styles, it's
often better to use CSS classes.
• You can add or remove classes using the classList property.

// Get a reference to the element


const myElement = document.getElementById("myElement");

// Add a CSS class


myElement.classList.add("highlight");

// Remove a CSS class


myElement.classList.remove("highlight");

133

Using the setAttribute Method:


You can also use the setAttribute method to modify any
attribute of an HTML element, including its style
attributes.
// Get a reference to the element
const myElement =
document.getElementById("myElement");

// Set the style attribute using setAttribute


myElement.setAttribute("style", "background-color: green;
color: white;");

134

67
Applying Changes to Multiple Elements:
You can use loops or query selectors to apply style changes to
multiple elements at once.
// Using a loop to apply styles to multiple elements
const elements = document.querySelectorAll(".my-class");
elements.forEach(element => {
element.style.fontSize = "18px";
});

// Using querySelectorAll to apply styles based on a CSS selector


const elements = document.querySelectorAll(".highlight");
elements.forEach(element => {
element.style.backgroundColor = "yellow";
});
135

The Document Tree


• In the context of the Document Object Model (DOM),
a "document tree" refers to the hierarchical structure
that represents the elements and their relationships
within an HTML or XML document.
• The DOM is a programming interface for web
documents, which allows scripts (typically written in
JavaScript) to interact with and manipulate the
content, structure, and style of web pages.
136

68
• The document tree in the DOM is organized as a tree-like
structure, where each element in the document (such as HTML
tags) is represented as a node in the tree.
• The top node of the tree is the "document" node, which
represents the entire web page. Below it, you have nodes
representing elements, attributes, and text content.
• Elements can have child nodes, which are nested elements
within them.
• This hierarchical structure reflects the nesting and
relationships between different elements in the HTML or XML
document.
137

69
DOM event handling
• DOM (Document Object Model) event handling is a
fundamental aspect of web development that allows you to
respond to interactions and actions that occur within a web
page.
• Events are user actions or occurrences that take place in the
browser, such as clicking a button, typing in an input field,
resizing the window, and more.
• Event handling involves specifying what should happen when
a particular event occurs and then executing the
corresponding code (event handler) in response.
139

Here's an overview of how DOM event handling works:


1. Event Types:
• There are numerous types of events that can occur, such as
"click," "mouseover," "keydown," "submit," "resize," and many
more.
• These events are triggered by user interactions or changes in
the browser environment.
2. Event Target:
• Each event is associated with a specific DOM element (the
event target) that is affected by the event.
• For instance, if you want to respond to a button click, you'll
140

70
3. Event Listener:
• An event listener is a piece of code that "listens" for a specific
event on a particular DOM element.
• When the event occurs, the event listener executes a function
(event handler) that you've defined.
4. Event Handler:
• The event handler is the function that gets executed when the
event is triggered.
• It contains the code that responds to the event. This code can
manipulate the DOM, update data, or perform other actions
based on the event.

Here's an example of attaching an event listener to a button element


using JavaScript:
// Get a reference to the button element
const button = document.getElementById("myButton");
// Define an event handler function
function handleClick(event) {
// Code to be executed when the button is clicked
console.log("Button clicked!");
}
// Attach the event listener to the button element
button.addEventListener("click", handleClick);
In this example, the addEventListener method is used to attach a
"click" event listener to the button element.
When the button is clicked, the handleClick function is called.

142

71
• Event handling is crucial for creating interactive and
dynamic web pages.
• It allows you to create responsive user interfaces and
enables users to interact with your web content in
meaningful ways.
• Different event types and event listeners provide
developers with a wide range of possibilities for
creating engaging user experiences.

143

jQuery
• JQuery is Easy to Learn
• JQuery is Lightweight

• jQuery is a JavaScript Library.

• jQuery greatly simplifies

JavaScript programming.

• More efficient and concise way to interact with the


Document Object Model (DOM)

72
jQuery Cont..
• "write less, do more", JavaScript library.
• perform common tasks on web pages.
• The purpose of jQuery is to make it much easier
to use JavaScript on your website.
• jQuery also simplifies a lot of the complicated
things from JavaScript, like AJAX calls and DOM
manipulation.

jQuery Cont..
The jQuery library contains the following features:
• HTML/DOM manipulation
• CSS manipulation
• HTML event methods
• Effects and animations
• AJAX
• Utilities

146

73
jQuery Cont..
jQuery Syntax
The jQuery syntax is tailor-made for selecting HTML elements
and performing some action on the element(s).

$(selector).action()

• A $ sign to define/access jQuery


• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)

147

jQuery Cont..
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with


class="test".
$("#test").hide() - hides the element with id="test".

148

74
jQuery Cont..
Adding jQuery to Your Web Pages

There are several ways to start using jQuery on your

web site. You can:

1. Download the jQuery library from jQuery.com

2. Include jQuery from a CDN, like Google

149

jQuery Cont..
Downloading jQuery
There are two versions of jQuery available for downloading:
Production version - this is for your live website because it has been
minified and compressed
Development version - this is for testing and development (uncompressed
and readable code)
Both versions can be downloaded from jQuery.com.
<head>
<script src="jquery-3.6.4.min.js"></script>
</head>

150

75
jQuery Cont..
jQuery CDN
If you don't want to download and host jQuery yourself, you
can include it from a CDN (Content Delivery Network).
Google is an example of someone who host jQuery:

Google CDN:
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/j
query.min.js"></script>
</head>
151

jQuery Cont..
jQuery Example: To hide Paragraph
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.j
s"> </script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script> </head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
</body>
152

76
jQuery Cont..
• jQuery Example: To change CSS Property
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).css("background-color","Red");
});
});
</script> </head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
</body>

jQuery Cont..
• jQuery Example: To append/Add element
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
> </script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).append("Hello");
});
});
</script> </head>
<body>
<p>If you click on me, I will modify.</p>
<p>Click me away!</p>
</body>
154

77
jQuery Cont..
jQuery Example: To remove element
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).remove();
});
});
</script> </head>
<body>
<p>If you click on me, I will remove.</p>
<p>Click me away!</p>
</body>

155

Angular JS
• AngularJS is a JavaScript framework.
• It can be added to an HTML page with a <script> tag.
• AngularJS extends HTML attributes with Directives,
and binds data to HTML with Expressions.
• Syntax
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/
1.6.4/angular.min.js"> </script>

156

78
Angular JS Cont…
AngularJS Extends HTML
• AngularJS extends HTML with ng-directives.
• The ng-app directive defines an AngularJS
application.
• The ng-model directive binds the value of HTML
controls (input, select, textarea) to application data.
• The ng-bind directive binds application data to the
HTML view.

AngularJS - MVC Architecture


Model View Controller or MVC as it is popularly called, is a
software design pattern for developing web applications.
A Model View Controller pattern is made up of the following
three parts −
Model − It is the lowest level of the pattern responsible for
maintaining data.
View − It is responsible for displaying all or a portion of the data
to the user.
Controller − It is a software Code that controls the interactions
between the Model and View.
158

79
The Model
• The model is responsible for managing application
data.
• It responds to the request from view and to the
instructions from controller to update itself.

The View
• A presentation of data in a particular format,
triggered by the controller's decision to present the
data.
• They are script-based template systems such as JSP,
ASP, PHP and very easy to integrate with AJAX
technology.

160

80
The Controller
The controller responds to user input and
performs interactions on the data model
objects.
The controller receives input, validates it, and
then performs business operations that modify
the state of the data model.

161

Angular JS Cont…
• Steps to create AngularJS
• Step 1 − Load framework- using <Script> tag.
<script src =
"https://ajax.googleapis.com/ajax/libs/
angularjs/1.3.14/angular.min.js"></script>
• Step 2 − Define AngularJS Application using ng-app
directive
<div ng-app = ""> ... </div>

81
Angular JS Cont…
• Step 3 − Define a model name using ng-model
directive
<p>Enter your Name: <input type = "text"
ng-model = "name"></p>
• Step 4 − Bind the value of above model defined using
ng-bind directive.
<p>Hello <span ng-bind = "name"></span>!</p>

163

Angular JS Cont…
AngularJS – Directives
• 1. ng-app − This directive starts an AngularJS
Application. It is also used to load various AngularJS
modules in AngularJS Application.
<div ng-app = ""> ... </div>
• 2. ng-init − This directive initializes application data.
It is used to put values to the variables to be used in
the application.
<div ng-app="" ng-init="firstName='John'">

82
Angular JS Cont…
• 3. ng-model − This directive binds the values of
AngularJS application data to HTML input controls.
<p>Enter your Name: <input type = "text" ng-
model = "name"></p>

165

Angular JS Example
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/ang
ular.min.js"></script>
<body>
<div ng-app="">
Name: <input type="text" ng-model="name">
<p ng-bind="name"></p>
</div>
</body>
</html>
166

83
Example explained:
AngularJS starts automatically when the web page has

loaded.

The ng-app directive tells AngularJS that the <div>

element is the "owner" of an AngularJS application.

The ng-model directive binds the value of the input

field to the application variable name.

The ng-bind directive binds the content of the <p>

element to the application variable name.


167

Angular JS Cont…
AngularJS Expression
Expressions are used to bind application data to
html.
Expressions are written inside double braces like
{{ expression}}
Using numbers
<p>Expense on Books : {{cost * quantity}} Rs</p>

168

84
Angular JS Cont…
Using strings
<p>Hello {{fname+ “ “ +lname }}</p>
Using object
<p>Roll No: {{student.rollno}}</p>
Using array
<p>Marks(Math): {{marks[3]}}</p>

169

Angular JS Cont…
• AngularJS Expressions –Example
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.
6.4/angular.min.js">
</script>
<body>
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
Output
</html>
My first expression : 10

170

85
Angular JS Cont…
• 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
• Each controller accepts $scope as a parameter which
refers to the application/module that controller is to
control.
<div ng-app="myApp" ng-controller="myCtrl">

171

Angular JS Cont…
AngularJS Controllers- Example
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>

172

86
Angular JS Cont…

OUTPUT

173

87
88

You might also like