0% found this document useful (0 votes)
13 views

Ch 01 CSS Aug-23

Uploaded by

addy26194
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Ch 01 CSS Aug-23

Uploaded by

addy26194
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 200

CHAPTER 01

Basics of
JavaScript Programming

1
Topics and Sub-topics:

1.1 Features of JavaScript


1.2 Object Name, Property, Method, Dot Syntax, Main
Event
1.3 Values and Variables
1.4 Operators and Expressions
1.5 if statement, if…else. If…else if , Nested if
1.6 switch… case statement
1.7 Loop statement
1.8 Querying and setting properties and Deleting
properties, Property Getters and Setters

2
SCRIPT
 A Script is generally a series of program or instruction,
which has to be executed on other program or
application.

 A Script is a small piece of program that can interact


to the website

 A Script could generate a pop-up alert box message,


or provide a drop down menu

 Script could be JavaScript or VBScript as we know


that the web works in a client-server environment.

3
TYPES OF SCRIPTING LANGUAGE

 Client side Scripting

 Server side Scripting

4
• The client-side script executes the code to the client side
which is visible to the users while a server-side script is
executed in the server end which users cannot see.

• The scripts can be written in two forms, at the server end


(back end) or at the client end (server end).

• The main difference between server-side scripting and


client-side scripting is that the server-side scripting involves
server for its processing.

• On the other hand, client-side scripting requires browsers to


run the scripts on the client machine but does not interact
with the server while processing the client-side scripts.

5
6
SERVER-SIDE SCRIPTING
• Server-side scripting is a technique of programming for
producing the code which can run software on the server
side, in simple words any scripting or programming that can
run on the web server is known as Server-side scripting.

•The operations like customization of a website, dynamic


change in the website content, response generation to the
user’s queries, accessing the database, and so on are
performed at the server end.

7
• The server-side scripting constructs a communication link
between a server and a client (user).

• Earlier the server-side scripting is implemented by the CGI


(Common Gateway Interface) scripts.

• The CGI was devised to execute the scripts from


programming languages such as C++ or Perl on the
websites.

8
 The server-side involves four parts: server, database,
API’s and back-end web software developed by the server-
side scripting language.

 When a browser sends a request to the server for a


webpage consisting of server-side scripting, the web server
processes the script prior to serving the page to the
browser.

 Here the processing of a script could include extracting


information from a database, making simple calculations,
or choosing the appropriate content that is to be displayed
in the client end.

9
 The script is being processed and the output is sent to the
browser.

 The web server abstracts the scripts from the end user
until serving the content, which makes the data and source
code more secure

10
The Programming languages for server-side programming
are:

1) PHP
2) C++
3) Java and JSP
4) Python
5) Ruby

11
CLIENT -SIDE SCRIPTING
 Client-side scripting is performed to generate a code that can run on
the client end (browser) without needing the server-side processing.

 Basically, these types of scripts are placed inside an HTML


document. The client-side scripting can be used to examine the user’s
form for the errors before submitting it and for changing the content
according to the user input.

 In Client-side scripting, the web requires three elements for its


functioning which are, client, database and server.

12
• The effective client-side scripting can significantly reduce
the server load.

• It is designed to run as a scripting language utilizing a


web browser as a host program.

• For example, when a user makes a request via browser


for a webpage to the server, it just sent the HTML and CSS
as plain text, and the browser interprets and renders the
web content in the client end.

13
The Programming languages for client-side programming
are:

1) JavaScript
2) VBScript
3) HTML
4) CSS (Cascading Style Sheet)
5) AJAX

14
BASIS FOR
COMPARISO SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING
N

Basic Works in the back end Works at the front end


which could not be and script are visible
visible at the client end. among the users.

Processin Requires server Does not need


g interaction. interaction with the
server.
Language PHP, ASP.net, Ruby on HTML, CSS, JavaScript,
s involved Rails, Python, etc. etc.

Affect Could effectively Can reduce the load to


customize the web the server.
pages and provide
dynamic websites.
Security Relatively secure. Insecure.

15
Why do we use javascript?

 Using HTML, we can only design a web page but you


cannot run any logic on web browser like addition of two
numbers, check any condition, looping statements (for,
while), decision making statement (if-else) at client side.

 All these are not possible using HTML So for perform all
these tasks at client side you need to use JavaScript.

16
Where JavaScript is Used?

• There are too many web applications running on the web


that are using JavaScript technology like Gmail, Facebook,
twitter, Google map, YouTube etc.

17
Following are some uses of JavaScript:

• Client-side validation

• Dynamic drop-down menus

• Displaying data and time

• Validate user input in an HTML form before sending


the data to a server.

18
 Build forms that respond to user input without
accessing a server.

 Change the appearance of HTML documents and


dynamically write HTML into separate Windows.

 Open and close new windows or frames.

 Manipulate HTML "layers" including hiding, moving,


and allowing the user to drag them around a browser
window.

19
Build small but complete client-side programs.

 Displaying popup windows and dialog boxes (like


alert dialog box, confirm dialog box and prompt dialog
box)

 Displaying clocks etc.

20
21
HTML – CSS - JS
 HTML is the markup language that we use to structure
and give meaning to our web content, for example
defining paragraphs, headings, and data tables, or
embedding images and videos in the page.

 CSS is a language of style rules that we use to apply


styling to our HTML content, for example setting
background colors and fonts, and laying out our content
in multiple columns.

 JavaScript is a scripting language that enables you to


create dynamically updating content, control multimedia,
22 animate images, and pretty much everything else.
FEATURES OF JAVASCRIPT

JavaScript is a client-side technology, it is mainly used for gives


client-side validation
JavaScript is an object-based scripting language.
Giving the user more control over the browser.
It Handling dates and time.
It Detecting the user's browser and OS,
It is light weighted.
JavaScript is a scripting language and it is not java.
JavaScript is interpreter-based scripting language.
JavaScript is case sensitive.

23
24
25
JavaScript is object-based language as it provides
predefined objects.

Every statement in JavaScript must be terminated with


semicolon (;)

Most of the JavaScript control statements syntax is


same as syntax of control statements in C language.

An important part of JavaScript is the ability to create


new functions within scripts. Declare a function in
JavaScript using function keyword.

26
ADVANTAGES OF JAVASCRIPT

Speed: Client-side JavaScript is very fast because it


can be run immediately within the client-side browser.

Simplicity: JavaScript is relatively simple to learn


and implement.

Popularity: JavaScript is used everywhere on the


web.

27
Interoperability: JavaScript plays nicely with other
languages and can be used in a huge variety of
applications.

Server Load: Being client-side reduces the demand on


the website server.

28
Light-weight and interpreted:
• JavaScript is a lightweight scripting language
because it is made for data handling at the browser
only.
• Since it is not a general-purpose language so it has a
limited set of libraries.
• Also, as it is only meant for client-side execution and
that too for web applications, hence the lightweight
nature of JavaScript is a great feature.

29
JavaScript is an interpreted language which means the
script written inside JavaScript is processed line by line.
These Scripts are interpreted by JavaScript interpreter
which is a built-in component of the Web browser.

30
Gives the ability to create rich interfaces.
Client-side Validations: This is a feature which is available
in JavaScript since forever and is still widely used because
every website has a form in which users enter values, and
to make sure that users enter the correct value, we must
put proper validations in place, both on the client-side and
on the server-side. JavaScript is used for implementing
client-side validations.

31
DISADVANTAGES OF JAVASCRIPT

• Security: As the code executes the user’s computer, in


some cases it can be exploited for malicious purpose.
• JavaScript done not read and write the files.
• JavaScript can not be used for networking applications.
• JavaScript does not have multi-threading and multi-
processing capabilities.
• JavaScript does not support overloading and overriding.

32
JS Programming

 A scripting language developed by Brendan Eich at


Netscape to enable web authors to design interactive
sites
 HTML is case in sensitive language whereas JS is case
sensitive
 HTML tags create object
 JS lets you manipulate those objects
 Example : <body> & </body> tags to create a web page
or document

33
ATTRIBUTES OF <SCRIPT>
 The <script> tag in HTML is used to define the client-
side script.
 The <script> tag contains the scripting statements,
or it points to an external script file.
 The JavaScript is mainly used in form validation,
dynamic changes of content, image manipulation,
etc.

<script> Script Contents... </script>

34
Many attribute associated with <script>

 async: It is used to specify the script is executed


asynchronously.
 charset: It is used to specify the character encoding
used in an external script file.
 defer: It is used to specify that the script is executed
when the page has finished parsing.
 src: It is used to specify the URL of an external
script file.
 type: It is used to specify the media type of the
script.

35
EXAMPLE
<html>

<head>
<script> // scripting code </script>
</head>

<body></body>
</html>

36
37
38
39
OBJECT NAME, PROPERTY, METHOD, DOT SYNTAX,
MAIN EVENT:

• JavaScript is an Object based scripting language.


• A JavaScript object is a collection of named values.
• These named values are usually referred to as Properties of the
object.
• A JavaScript objects are collection of Properties and Methods.

 A Method is a function that is a member of an object.


 A Property is a value or set of values that is the member of an
object.

40
In JavaScript, almost "everything" is an
object.

 Booleans can be objects (if defined with the new keyword)


 Numbers can be objects (if defined with the new keyword)
 Strings can be objects (if defined with the new keyword)
 Dates are always objects.
 Maths are always objects
 Regular expressions are always objects.
 Arrays are always objects.
 Functions are always objects.
 Objects are always objects.

41
OBJECT NAME:

• Each object is uniquely identified by a name or ID.


• With JavaScript, you can define and create your own
objects.

42
There are different ways to create new
objects:

A. Define and create a single object, using an object


literal.
B. Define and create a single object, with the keyword
“new”
OR
- by creating instance of Object

43
A. DEFINE AND CREATE A SINGLE OBJECT,
USING AN OBJECT LITERAL.

 Using an object literal, you both define and create an


object in one statement.

 An object literal is a list of names: value pairs (like


age:10) inside curly braces { }.

44
• The following example creates a new JavaScript object
with 3 properties:
E.g.
var person = {
firstName: “Hhh",
lastName: “Bbb",
age: 10
};
• In above example, person is an object and firstName ,
lastName and age are three properties.
• “Hhh” , “Bbb” and 10 these are values associated with
properties.

45
Code:
<html>
<body>
<script>
emp={ id:"VP-179",name:"Aaa Bbb",salary:50000 }
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>

Outpu
VP-179 Aaa Bbb 50000
t:

46
B. Define and create a single object, with the
keyword “new” OR by creating instance of
Object
new keyword is used to create object.
Syntax: var objectname=new Object();

Example:
var person = new Object();
person.firstName = “Hhh";
person.age = 10;

47
Code:

<html>
<body>
<script>
var emp=new Object();
emp.id="VP-179";
emp.name="Aaa ";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
VP-179 Aaa 50000
</body>
</html> Output

48
C. Define an object constructor, and then create objects
of the constructed type.

• Here, you need to create function with arguments.


• Each argument value can be assigned in the current
object by using this keyword.
• The this keyword refers to the current object.

49
Example:
function person(firstName, lastName, age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
p=new person(“aaa”,”vvv”,10);
document.write(p.firstName+" "+p.lastName+" "+p.age);

50
Code:
<html>
<body>
<script>
function emp(id,name,salary)
{
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp("VP-179","Aaa ",50000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html> Output: VP-179 Aaa 50000

51
TYPES OF OBJECTS:

• Native Objects/ Built-in Objects: are those objects


supplied by JavaScript.

 Examples of these are Math, Date, String, Number,

Array, Image, etc.

52
1) Math:
Math Properties

Math Property Description

SQRT2 Returns square root of 2.


PI Returns Π value.
E Returns Euler's Constant.
LN2 Returns natural logarithm of 2.
LN10 Returns natural logarithm of 10.

LOG2E Returns base 2 logarithm of E.


LOG10E Returns 10 logarithm of E.

53
<html>
<head>
<title>JavaScript Math Object Properties</title>
</head>
<body>
<script type="text/javascript">
var value1 = Math.E;
document.write("E Value is :" + value1 + "<br>");
var value3 = Math.LN10;
document.write("LN10 Value is :" + value3 + "<br>");
var value4 = Math.PI;
document.write("PI Value is :" + value4 + "<br>");
</script>
</body>
E Value is :2.718281828459045
</html> Output:
LN10 Value is :2.302585092994046
PI Value is :3.141592653589793

54
Math Methods

Math Methods Description

abs() Returns the absolute value of a number.


acos() Returns the arccosine (in radians) of a number.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns cosine of a number.
floor() Returns the largest integer less than or equal to a number.
log() Returns the natural logarithm (base E) of a number.

max() Returns the largest of zero or more numbers.

min() Returns the smallest of zero or more numbers.


pow() Returns base to the exponent power, that is base exponent.

55
56
<html>
<body>
<script type="text/javascript">
var value = Math.abs(-20);
document.write("ABS Value : " + value +"<br>");
var value = Math.tan(5);
document.write("TAN Value : " + value +"<br>");
</script>
</body>
</html>

Output: ABS Value: 20


TAN Value : -3.380515006246586

57
2) Date

Syntax: Date is a data type.

var variable_name = new Date();

•Date object manipulates date and time.


•Date() constructor takes no arguments.
•Date object allows you to get and set the year, month, day,
hour, minute, second and millisecond fields.

Example:

58
var current_date = new Date();
Date
Methods:
Date Methods Description
Date() Returns current date and time.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getFullYear() Returns the year.
getHours() Returns the hour.
getMinutes() Returns the minutes.
getSeconds() Returns the seconds.

getMilliseconds() Returns the milliseconds.

getTime() Returns the number of milliseconds since January


1, 1970 at 12:00 AM.
getTimezoneOff Returns the timezone offset in minutes for the
set() current locale.
getMonth() Returns the month.
setDate() Sets the day of the month.
setFullYear() Sets the full year.

59
Date Methods Description

setHours() Sets the hours.


setMinutes() Sets the minutes.

setSeconds() Sets the seconds.

setMilliseconds() Sets the milliseconds.

setTime() Sets the number of milliseconds since January


1, 1970 at 12:00 AM.
setMonth() Sets the month.
toDateString() Returns the date portion of the Date as a
human-readable string.
toLocaleString() Returns the Date object as a string.

toGMTString() Returns the Date object as a string in GMT


timezone.
valueOf() Returns the primitive value of a Date object.

60
Code:
<html>
<body>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = new Date();
document.write("<b>Locale String:</b> " + d.toLocaleString()+"<br>");
document.write("<b>Hours:</b> " + d.getHours()+"<br>");
document.write("<b>Day:</b> " + d.getDay()+"<br>");
document.write("<b>Month:</b> " + d.getMonth()+"<br>");
document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
</script>
</body>
Date Methods
</html> Locale String: 7/3/2020,In above code, getMonth() will returns 6
5:23:19 PM since months starts from 0 that is
Hours: 17 0-> January , 1->February
Day: 5 2-> March , 3 ->April
Month: 6 And so on.
FullYear: 2020
Minutes: 23

61
62
3) String
String objects are used to work with text.
It works with a series of characters.

Syntax:
var variable_name = new String(string);

Example:
var s = new String(string);

63
String Properties:
String Description
methods
charAt() It returns the character at the specified
index.
charCod It returns the ASCII code of the
eAt() character at the specified position.
concat() It combines the text of two strings and
returns a new string.
indexOf It returns the index within the calling
() String object.
match() It is used to match a regular expression
against a string.
replace( It is used to replace the matched
) substring with a new substring.

64
search() It executes the search for a match
String methods Description
slice() It extracts a session of a string and returns
a new string.
split() It splits a string object into an array of
strings by separating the string into the
substrings.
toLowerCase() It returns the calling string value converted
lower case.
toUpperCase() Returns the calling string value converted
to uppercase.

65
<html>
<body>
<script type="text/javascript">
var str = "A JavaScript";
document.write("<b>Char At:</b> " + str.charAt(4)+"<br>");
document.write("<b>CharCode At:</b> " +
str.charCodeAt(0)+"<br>");
document.write("<b>Index of:</b> " + str.indexOf(“p")
+"<br>");
document.write("<b>Lower Case:</b> " + str.toLowerCase()
+"<br>");
document.write("<b>Upper Case:</b> " + str.toUpperCase()
+"<br>");
</script>
</body></html>
Char At: v
CharCode At: 65
Index of: 10
Lower Case: a javascript
Upper Case: A JAVASCRIPT

66
• Host Objects: are objects that are supplied to
JavaScript by the browser environment.
• Examples of these are window, document, forms, etc.

Window:
• The window object represents a window in browser.
• An object of window is created automatically by the
browser.
• Window is the object of browser; it is not the object of
javascript.

67
Window Methods:

Window Description
methods
alert() displays the alert box containing message with
ok button.
confirm() displays the confirm dialog box containing
message with ok and cancel button.
prompt() displays a dialog box to get input from the user
along with with ok and cancel button.
open() opens the new window.
close() closes the current window.

68
69
70
71
72
73
74
75
<script type="text/javascript">
function msg()
{
var a= window.prompt("Who are you?");
window.alert("I am "+a);
}
</script>
<input type="button" value="click" onclick="msg()">

76
77

•User-Defined Objects: are those that are defined by you,
the programmer.

Property:

• Properties are the values associated with a JavaScript


object.

•A JavaScript object is a collection of unordered properties.

•Properties can usually be changed, added, and deleted,


but some are read only.

78
The syntax for accessing the property of an object
is:

objectName.property // person.age

objectName["property"] // person["age"]

objectName[expression] // x = "age"; person[x]

79
Dot Operator:

The properties and methods associated with any object


can be accessed by using dot(.) Operator.

Example, emp.id or op.add();

Dot operator is used to how to interact with objects,


methods, events and properties.

Dot operator is also used to add new property.

Example, emp.designation=“Lecturer”;

80
<html>
<body>
<script>
var person =
{
firstname:"Hhh",
age:10
};
person.std = "Fifth"; //adding new property as “std”
document.write(person.firstname+" "+"is in "+person.std+"
standard"); //Accessing properties with dot
</script>
</body></html>

Hhh is in Fifth standard

81
Methods:

JavaScript methods are actions that can be performed


on objects.

A JavaScript function is a block of code designed to perform


a particular task.

A JavaScript function is defined with the function keyword,

followed by a name, followed by parentheses ().

The parentheses may include parameter names separated


by commas:
(parameter1, parameter2, ...)

82
The code to be executed, by the function, is placed inside
curly brackets: { }

Syntax:

function name(parameter1, parameter2, parameter3)


{
// code to be executed
}

83
Code: simple method to define a function

<html>
<body>
<script>
function op_add(p1, p2)
{
return p1 + p2;
}
document.write("Addition is="+op_add(4, 5));
</script>
</body>
</html> Addition is=9

84
Code: define a function as a property
<script>
var person =
{
firstname:"Hhh",
lastname:"Bbb",
Fullname:function() // define a function as a property
{
return this.firstname+" "+this.lastname;
}
};
document.write("Person Detail is="+person.Fullname());
</script>

Output : Person Detail is = Hhh Bbb

85
Code: define a function as an expression
<script>
var x = function (a, b) // function as an expression
{
return a * b ;
}
document.write("function returns= " +x(4, 5));
</script>
function returns= 20

Output:

function returns= 20

86
Main Event:

•An Event is an action performed by user or web browser.

•In order to make a web pages more interactive, the script needs to be
accessed the contents of the document and know when the user is
interacting with it.

Events may occur due to:


1) a document loading
2) user clicking on mouse button
3) browser screen changing size

87
Here are some examples of HTML events:

• An HTML web page has finished loading


• An HTML input field was changed
• An HTML button was clicked
• Event handlers can be used to handle, and verify,
user input,
user actions, and browser actions:

88
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an
HTML element
onmouseout The user moves the mouse away from
an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the
page

89
<html>
<head>
<script type="text/javascript">
function msg()
{
alert("Hello IF5I students");
}
</script>
</head>
<body>
<center>
<p><h1>Welcome to Client-side scripting</h1></p>
<form>
<input type="button" value="click" onclick ="msg()"/>
// onclick event
</form>
</body>

90
</html>
91
DOM GETELEMENTBYID()

 The getElementById() method returns the elements that


has given ID which is passed to the function.

 This function is widely used in web designing to change


the value of any particular element or get a particular
element.

92
Syntax: document. getElementById(element_id) ;

 Parameter: This function accepts single


parameter element_id which is used to hold
the ID of element.

 Return Value: It returns the object of given ID. If no


element exists with given ID then it returns
null.

93
<html>
<body>
<p id="demo">Click the button to change the color of this paragraph.</p>
<button onclick="myFunction()">change color</button>
<script>
function myFunction()
{
var x = document.getElementById("demo");
x.style.color = "red";
}
</script>
</body>
</html>

94
Basic concept in JS

95
96
97
Values and Variables

In JavaScript there are two types of scope:


• Local scope
• Global scope

JavaScript has function scope: Each function creates a


new scope.
Scope determines the accessibility (visibility) of these
variables.
Variables defined inside a function are not accessible
(visible) from outside the function.

98
There are some rules while declaring a JavaScript variable
(also known as identifiers).

Name must start with a letter (a to z or A to Z),


underscore( _ ), or dollar( $ ) sign.
After first letter we can use digits (0 to 9), for example
value1.
JavaScript variables are case sensitive, for example x
and X are different variables.
We can say that variable is a container that can be used
to store value and you need to declare a variable before
using it.

99
JavaScript Syntax for Declaring a Variable

Following is the syntax for declaring a variable and


assigning values to it.

var varible-name;

We can also define a variable without using the semicolon


too. Also, when we have to define multiple variables, we
can do it like this:
var x,y,z;

100
JavaScript Variable Example:
Now let's take a simple example where we will declare a
variable and then assign it a value.

var emp_name;
var emp_name=“Amaan”;

101
JAVASCRIPT: TYPES OF VARIABLES

JavaScript supports two types of variables, they are:


 Local Variable
 Global Variable

You can use them according to the requirement in the application.

Let's learn about both JavaScript Local variables and JavaScript Global
variables with examples.

102
1. JavaScript Local Variable

 JavaScript Local variable is a variable that is declared inside a code


block or a function body or inside a loop body and it has scope within
the code block or the function.
 In simple words, the scope of a local variable is between the
opening and closing curly braces { }, when declared and defined
inside a code block or a function body.

 A JavaScript local variable is declared inside block or function.


 It is accessible within the function or block only.

103
LOCAL VARIABLE EXAMPLE
<script>
function abc()
{
var x=10; //x is a local variable
}
</script>

104
JAVASCRIPT GLOBAL VARIABLE

 JavaScript Global Variable is a variable that is declared anywhere


inside the script and has scope for the complete script execution.

Global variables are not declared inside any block or function but
can be used in any function, or block of code.

 A JavaScript global variable is accessible from any function.

 A variable i.e. declared outside the function or declared with


window object is known as Global variable.

105
<html>
<body>
<script>
var data=200; //global variable
function a( )
{
document.write(data);
}
function b( )
{
document.write(data);
200 200
}
a( ); //calling JavaScript function
b( );
</script></body></html>

106
DATA TYPES

JavaScript provides different data types to hold different


types of values.

There are two types of data types in JavaScript:

• Primitive data type


• Non-primitive (reference) data type/ Composit Data Types

107
JavaScript is a dynamic type language; means you don't
need to specify type of the variable.

 You need to use var here to specify the data type.


 It can hold any type of values such as numbers, strings
etc.

 For example:
var a=40; //holding number
var b=“Info Technology”; //holding string

108
JavaScript Data Types

Non-Primitive
Primitive (Primary)
(Composite)

Nu Und
Stri
mb
Boo
efin Null Functi
ng lean Object Array
er ed on

109
DATA TYPES: PRIMITIVE

Primitive data types can hold only one value at a time.


1) The String Data Type
The string data type is used to represent textual data (i.e.
sequences of characters).

Strings are created using single or double quotes


surrounding one or more characters, as shown below:
var a = ‘Welcome'; // using single quotes
var b = “Welcome”;// using double quotes

110
2. The Number Data Type

• The number data type is used to represent positive or negative


numbers with or without decimal place.
• The Number data type also includes some special values which
are: Infinity,-Infinity, NaN(Not a Number)

Example,
var a = 25; // integer
var b = 80.5; // floating-point number
var c = 4.25e+6; // exponential notation, same as 4.25e6 or
4250000
var d = 4.25e-6; // exponential notation, same as 0.00000425

111
3) The Boolean Data Type

 The Boolean data type can hold only two values:


True/False

Example,
var a = 2, b = 5, c = 10;
alert(b > a) // Output: true
alert(b > c) // Output: false

112
4) The Undefined Data Type

 The undefined data type can only have one value-


the special value “undefined”.
 If a variable has been declared, but has not been
assigned a value, has the value ”undefined”.

Example,
var a;
var b = “Welcome”;
alert(a) // Output: undefined
alert(b) // Output: Welcome

113
5) The Null Data Type

• A Null value means that there is no value.


• It is not equivalent to an empty string (“ “) or zero
or it is simply nothing.

114
Example,
var a = null;
alert(a); // Output: null
var b = "Hello World!“
alert(b); // Output: Hello World!
b = null;
alert(b) // Output: null

115
DATA TYPES: NON-PRIMITIVE
1) The Object Data Type
• A complex data type that allows you to store collections
of data.
• An object contains properties, defined as a key-value
pair.
• A property key (name) is always a string, but the value
can be any data type, like strings, numbers, Boolean, or
complex data types like arrays, function and other objects.
Example
var car =
{ model: “SUZUKI", color: “WHITE", model_year: 2019 }

116
2) The Array Data Type

 An array is a type of object used for storing multiple


values in single variable.

 Each value (also called an element) in an array has a


numeric position, known as its index, and it may contain
data of any data type-numbers, strings, Booleans,
functions, objects, and even other arrays.

 The array index starts from 0, so that the first array


element is arr[0].

117
 The simplest way to create an array is by specifying the
array elements as a comma-separated list enclosed by
square brackets

Example

var cities = ["London", "Paris", "New York"];


alert(cities[2]); // Output: New York
var a = ["London", 500, ”aa56”, 5.6];

118
3) The Function Data Type

 The function is callable object that executes a block of code.


 Since functions are objects, so it is possible to assign them
to variables, as shown in the example below:

var ab = function()
{
return “Welcome”;
}
alert(typeof ab); //output: function
alert(ab()); //output: Welcome

119
<html>
<body>
<h1>JavaScript Array</h1>
<script>
var stringArray = ["one", "two", "three"];
var mixedArray = [1, "two", "three", 4];
document.write(stringArray+"<br>");
document.write( mixedArray);
</script> JavaScript Array
</body> one,two,three
1,two,three,4
</html>

120
VALUES/LITERALS
 They are types that can be assigned a single literal value such
as the number 5.7, or a string of characters such as "hello".

Types of Literals:

Array Literal
Integer Literal
Floating number Literal
Boolean Literal (include True and False)
Object Literal
String Literal

121
Array Literal:
 an array literal is a list of expressions, each of which represents
an array element, enclosed in a pair of square brackets ' [ ] ‘

When an array is created using an array literal, it is initialized


with the specified values as its elements, and its length is set to
the number of arguments specified.

Creating an empty array :


var tv = [ ];
Creating an array with four elements.
var tv = [“LG", “Samsung", “Sony", “Panasonic"];

122
Comma in array literals:
In the following example, the length of the array is four, and tv[0] and
tv[2] are undefined.
var tv = [ , “Samsung“, , “Panasonic"];

This array has one empty element in the middle and two elements
with values.

( tv[0] is “LG", tv[1] is set to undefined, and tv[2] is “Sony")


Var tv = [“LG", ,“Sony", ];

123
Integer Literal:

An integer must have at least one digit (0-9).


• No comma or blanks are allowed within an
integer.
• It does not contain any fractional part.
• It can be either positive or negative if no sign
precedes it is assumed to be positive.

124
In JavaScript, integers can be expressed in three different bases.

1. Decimal ( base 10)


Decimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7,
8, 9 and there will be no leading zeros.

Example: 123, -20, 12345

2. Hexadecimal ( base 16)


Hexadecimal numbers can be made with the digits 0, 1, 2, 3, 4, 5,
6, 7, 8, 9 and letters A, B, C, D, E, F or a, b, c, d, e, f.
A leading 0x or 0X indicates the number is hexadecimal.

Example: 7b, -14, 3039

125
3. Octal (base 8)

Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7.


A leading 0 indicates the number is octal.

Example: 0173, -24, 30071

126
Floating number Literal:
A floating number has the following parts.
• A decimal integer.
• A decimal point ('.').
• A fraction.
• An exponent.

The exponent part is an "e" or "E" followed by an integer, which can be


signed (preceded by "+" or "-").

Example of some floating numbers:


8.2935
-14.72
12.4e3 [ Equivalent to 12.4 x 103]
4E-3 [ Equivalent to 4 x 10-3 => .004]

127
Object Literal:
An object literal is zero or more pairs of comma-separated list of
property names and associated values, enclosed by a pair of curly
braces.

In JavaScript an object literal is declared as follows:

1. An object literal without properties:

var userObject = { }

2. An object literal with a few properties :


var student = {
First-name : "Suresy",
Last-name : "Rayy",
Roll-No : 12

128
};
Syntax Rules

There is a colon (:) between property name and value.


A comma separates each property name/value from the
next.
There will be no comma after the last property name/value
pair.

129
String Literal:

JavaScript has its own way to deal with string literals.


A string literal is zero or more characters, either enclosed
in single quotation (') marks or double quotation (") marks.
You can also use + operator to join strings.

The following are the examples of string literals:


• string1 = "w3resource.com"
string1 = 'w3resource.com’
• string1 = "1000“

130
Special characters in JavaScript:

Character Description
\’ Single quote
\” Double quote
\\ Backslash
\b Backspace
\f Form Feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab

131
Comments in JavaScript:

The JavaScript comments are meaningful way to


deliver message.

 It is used to add information about the code, warnings


or suggestions so that end user can easily interpret the
code.

The JavaScript comment is ignored by the JavaScript


engine i.e. embedded in the browser.

132
There are two types of comments in JavaScript.
1. Single-line Comment
It is represented by double forward slashes (//).
It can be used before and after the statement.

Example,
<script>
// It is single line comment
document.write("hello javascript");
</script>

133
2. Multi-line Comment

It can be used to add single as well as multi line comments.


It is represented by forward slash with asterisk then asterisk with
forward slash.

Example,
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>

134
OPERATORS AND EXPRESSION

JavaScript operators are symbols that are used to perform


operations on operands.
• Arithmetic Operators
• Comparison (Relational) Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Special Operators

135
Arithmetic Operators: used to perform arithmetic
operations on the operands.

Operator Description Example

+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus 20%10 = 0
++ Increment var a=10; a++;
Now a = 11
-- Decrement var a=10; a--;
Now a = 9

136
<html> document.write("a % b = ");
<body> result = a % b;
<script type = "text/javascript"> document.write(result+"<br>");
var a = 33; document.write("a + b + c = ");
var b = 10; result = a + b + c;
var c = "Test"; document.write(result+"<br>");
document.write("a + b = "); a = ++a;
result = a + b; document.write("++a = ");
result = ++a;
document.write(result+"<br>"); document.write(result+"<br>");
document.write("a - b = "); b = --b;
result = a - b; document.write("--b = ");
result = --b;
document.write(result+"<br>"); document.write(result+"<br>");
document.write("a / b = "); </script></body></html>
result = a / b;

document.write(result+"<br>");

137
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8

138
2) Comparison (Relational) Operators: compares the two operands

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

139
<html><body>
result = (a != b);
<script type = "text/javascript">
document.write(result+"<br>");
var a = 10;
document.write("(a >= b) => ");
var b = 20;
result = (a >= b);
document.write("(a == b) => ");
document.write(result+"<br>");
result = (a == b);
document.write("(a <= b) => ");
document.write(result+"<br>");
result = (a <= b);
document.write("(a < b) => ");
document.write(result+"<br>");
result = (a < b);
</script>
document.write(result+"<br>");
</body>
document.write("(a > b) => ");
</html>
result = (a > b);
document.write(result+"<br>"); (a == b) => false
document.write("(a != b) => "); (a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
(a <= b) => true

140
BITWISE OPERATOR

 It perform bitwise operations on operands

141
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 (10>>>2) = 2


with Zero

142
<script type="text/javascript"> ;
var a = 2; // Bit document.write("(~b) => ");
presentation 10 result = (~b);
var b = 3; // Bit
presentation 11 document.write(result+"<br>")
document.write("(a & b) ;
=> "); document.write("(a << b) =>
result = (a & b); ");
result = (a << b);
document.write(result+"<br>");
document.write("(a | b) document.write(result+"<br>")
=> "); ;
result = (a | b); document.write("(a >> b) =>
");
document.write(result+"<br>"); result = (a >> b);
document.write("(a ^ b)
=> "); (a & b) => 2 document.write(result+"<br>")
result ;
(a | b) =
=> 3(a ^ b);
</script>
(a ^ b) => 1
(~b) => -4 </body>
(a << b) => 16 </html>

143
(a >> b) => 0
Logical Operator:

Operator Description Example

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


|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true

144
<html>
<body>
<script type = "text/javascript">
var a = true;
var b = false;
document.write("(a && b) => ");
result = (a && b);
document.write(result+"<br>"); (a && b) => false
document.write("(a || b) => "); (a || b) => true
result = (a || b); !(a && b) => true
document.write(result+"<br>");
document.write("!(a && b) => ");
result = (!(a && b));
document.write(result+"<br>");
</script>
</body>
</html>

145
5) ASSIGNMENT OPERATOR:

Operator Description Example

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

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


assign
*= Multiply and var a=10; a*=20; Now a =
assign 200
/= Divide and var a=10; a/=2; Now a = 5
assign
%= Modulus and var a=10; a%=2; Now a = 0
assign

146
SPECIAL OPERATOR:
Operator Description
(?:) Conditional Operator/ternary returns value based on the
condition.
It is like if-else.
, Comma Operator allows multiple expressions to be
evaluated as single statement
delete Delete Operator deletes a property from the object

in In Operator checks if object has the given property

instance checks if the object is an instance of given type


of
new creates an instance (object)
typeof checks the type of object
void it discards the expression's return value

147
Code : typeof operator
<html>
<body>
<script type = "text/javascript">
var a = 10;
var b = "Information";
var c= function(x)
{
return x*x;
}
document.write(typeof a+"<br>"); // a=10 data type is number
document.write(typeof b+"<br>"); // b="Information" is a string
document.write(typeof c+"<br>"); // c= function
document.write(c(4));
</script></body></html>

number
string
function

148
16
Code: Ternary (? :) operator

<script type = "text/javascript">


<script type = "text/javascript"> var a = 10;
var a = 10; var b = 20;
var b = 20; if(a>=b)
r=(a>=b)? "a is large":"b is large"; document.write("a is
large");
document.write(r); else
</script> document.write("b is
large");
</script>

In above example, if else can be replaced with ternary operator.

b is large

149
JavaScript Operator Precedence and Associativity

Operator precedence determines the order in which


operators are evaluated. Operators with higher precedence are
evaluated first.
For example, the expression (3+4*5), returns 23, because of
multiplication operator(*) having higher precedence than
addition(+). Thus * must be evaluated first.
Operator associativity determines the order in which
operators of the same precedence are processed.

For example, assignment operators are right-associative, so


you can write a=b=5, and with this statement, a and b are
assigned the value 5.

150
EXPRESSION:

Any unit of code that can be evaluated to a value is an


expression.
Since expressions produce values, they can appear
anywhere in a program where JavaScript expects a value
such as the arguments of a function invocation.

151
Types of Expression:

1. Primary Expression:
Primary expressions refer to stand alone expressions
such as literal values, certain keywords and variable
values.

'hello world'; // A string literal


23; // A numeric literal
true; // Boolean value true
sum; // Value of variable sum
this; // A keyword that evaluates to the current object.

152
2. Object and Array Initializers

Object and array initializers are expressions whose value is a


newly created object or array.
Object initializer expressions uses curly brackets, and each
subexpression is prefixed with a property name and a colon.
Example
var emp={ name:”Aaa”, branch:“IF”};
OR
var person={ };
person.name=“Aaa”;
person.branch=“IF”;
 An array initializer is a comma-separated list of expressions
surrounded with a square bracket.

153
Example, var tv=[“LG”, ”Samsung”];
3.

Property Access Expressions

A property access expression evaluates to the value of an object


property or an array element.

JavaScript defines two syntaxes for property access:


expression.identifier;
expression[identifier];

Example:
emp.firstName;
emp[lastName];

154
4. Function Definition Expression

A function expression is part of a variable assignment


expression and may or may not contain a name.

Since this type of function appears after the assignment


operator =, it is evaluated as an expression.

Function expressions are typically used to assign a


function to a variable.

155
Function expressions are evaluated only when the
interpreter reaches the line of code where function
expressions are located.

Example:
var sq=function (x)
{
return x*x;
}

156
5. Invocation Expression

An Invocation Expression is JavaScript’s syntax for


calling (or executing) a function or method.
It starts with a function expression that identifies the
function to be called.
 The function expression is followed by an open
parenthesis, a comma-separated list of zero or more
argument expressions, and a close parenthesis.
When an invocation expression is evaluated, the
function expression is evaluated first, and then the
argument expressions are evaluated to produce a list
of argument values.

157
Example,
f(0) // f is the function expression;
0 is the argument expression
Math.max(x,y,z) // Math.max is the function;
x, y and z are the arguments.

<script type = "text/javascript">


var obj = { add: function(a, b)
{ return a + b;
}};
alert(obj.add(4,5));
delete obj.add;
alert(obj.add(9,5));

158
</script>
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
<script type = "text/javaScript">
var lang = { first : "C", second : "Java",third : "Python", fourth :
“PHP"};
for (prog in lang)
{
document.write(lang[prog] + "<br >");
}
</script>
Output :
C
Java
Python
PHP

178
179
Output :

Navigator Object Properties


serviceWorker
webkitPersistentStorage
webkitTemporaryStorage
geolocation
doNotTrack
onLine
languages
language
userAgent
product
platform
appVersion
appName
appCodeName
hardwareConcurrency
maxTouchPoints
vendorSub
vendor
productSub
cookieEnabled
mimeTypes
plugins
javaEnabled
getStorageUpdates
getGamepads
webkitGetUserMedia
vibrate
getBattery
sendBeacon
registerProtocolHandler
unregisterProtocolHandler

180
Exiting from the loop!
181
182
183
184
While Loop Do – While Loop

In while loop, first it checks the In Do – While loop, first it


condition and then executes the
program. executes the program and then
checks the condition.
It is an entry – controlled loop. It is an exit – controlled loop.

The condition will come before The condition will come after the
the body. body.
If the condition is false, then it It runs at least once, even though
terminates the loop. the conditional is false.

It is a counter-controlled loop. It is a iterative control loop.

185
186
187
188
189
Querying & setting properties

190
191
192
193
194
195
196
Accessor Property

In JavaScript, accessor properties are methods that get or set the value of
an object. For that, we use these two keywords:

get - to define a getter method to get the property value


set - to define a setter method to set the property value

197
198
199
Thank You

200

You might also like