Ch 01 CSS Aug-23
Ch 01 CSS Aug-23
Basics of
JavaScript Programming
1
Topics and Sub-topics:
2
SCRIPT
A Script is generally a series of program or instruction,
which has to be executed on other program or
application.
3
TYPES OF SCRIPTING LANGUAGE
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.
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.
7
• The server-side scripting constructs a communication link
between a server and a client (user).
8
The server-side involves four parts: server, database,
API’s and back-end web software developed by the server-
side scripting language.
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.
12
• The effective client-side scripting can significantly reduce
the server load.
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
15
Why do we use javascript?
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?
17
Following are some uses of JavaScript:
• Client-side validation
18
Build forms that respond to user input without
accessing a server.
19
Build small but complete client-side programs.
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.
23
24
25
JavaScript is object-based language as it provides
predefined objects.
26
ADVANTAGES OF JAVASCRIPT
27
Interoperability: JavaScript plays nicely with other
languages and can be used in a huge variety of
applications.
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
32
JS Programming
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.
34
Many attribute associated with <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:
40
In JavaScript, almost "everything" is an
object.
41
OBJECT NAME:
42
There are different ways to create new
objects:
43
A. DEFINE AND CREATE A SINGLE OBJECT,
USING AN OBJECT LITERAL.
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.
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:
52
1) Math:
Math Properties
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
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>
57
2) Date
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.
59
Date Methods Description
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:
78
The syntax for accessing the property of an object
is:
objectName.property // person.age
objectName["property"] // person["age"]
79
Dot Operator:
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>
81
Methods:
82
The code to be executed, by the function, is placed inside
curly brackets: { }
Syntax:
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>
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:
•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.
87
Here are some examples of HTML events:
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()
92
Syntax: document. getElementById(element_id) ;
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
98
There are some rules while declaring a JavaScript variable
(also known as identifiers).
99
JavaScript Syntax for Declaring a Variable
var varible-name;
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
Let's learn about both JavaScript Local variables and JavaScript Global
variables with examples.
102
1. JavaScript Local Variable
103
LOCAL VARIABLE EXAMPLE
<script>
function abc()
{
var x=10; //x is a local variable
}
</script>
104
JAVASCRIPT GLOBAL VARIABLE
Global variables are not declared inside any block or function but
can be used in any function, or block of code.
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
107
JavaScript is a dynamic type language; means you don't
need to specify type of the variable.
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
110
2. The Number Data Type
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
Example,
var a = 2, b = 5, c = 10;
alert(b > a) // Output: true
alert(b > c) // Output: false
112
4) The Undefined Data Type
Example,
var a;
var b = “Welcome”;
alert(a) // Output: undefined
alert(b) // Output: Welcome
113
5) The Null Data Type
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
117
The simplest way to create an array is by specifying the
array elements as a comma-separated list enclosed by
square brackets
Example
118
3) The Function Data Type
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 ' [ ] ‘
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.
123
Integer Literal:
124
In JavaScript, integers can be expressed in three different bases.
125
3. Octal (base 8)
126
Floating number Literal:
A floating number has the following parts.
• A decimal integer.
• A decimal point ('.').
• A fraction.
• An exponent.
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.
var userObject = { }
128
};
Syntax Rules
129
String Literal:
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:
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
Example,
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
134
OPERATORS AND EXPRESSION
135
Arithmetic Operators: used to perform arithmetic
operations on the operands.
+ 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
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
141
Operator Description Example
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:
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:
= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
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
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
b is large
149
JavaScript Operator Precedence and Associativity
150
EXPRESSION:
151
Types of Expression:
1. Primary Expression:
Primary expressions refer to stand alone expressions
such as literal values, certain keywords and variable
values.
152
2. Object and Array Initializers
153
Example, var tv=[“LG”, ”Samsung”];
3.
Example:
emp.firstName;
emp[lastName];
154
4. Function Definition Expression
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
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.
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 :
180
Exiting from the loop!
181
182
183
184
While Loop Do – While 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.
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:
197
198
199
Thank You
200