3. 3
SCRIPTING LANAGUAGE
JAVASCRIPT BASICS
OPERATORS & CONTROL STRUCTURES
JAVASCRIPT FUNCTION
OBJECTS : Array , String , Math & Date
DOM - Document Object Model
JAVASCRIPT EVENTS
4. JAVASCRIPT BASICS
• SCRIPTING LANAGUAGE
Scripting Language are programming languages
used to write web based programs.
4
5. Need for Scripting Language
• Validating the input data given
• To add different menu styles, graphics displays
• We can create new variables without specifying
the type.
5
6. Need for Scripting Language
• Data type conversion takes place automatically
• We can write event driven programs
–Mouse event , keyboard event
6
7. Easily & Fast - Scripting Programs
• Java Script is one of the
scripting languages
7
9. What JavaScript Can do For us?
• used to insert dynamic text into the HTML
ex: Name, Address
• react to events (for example, load the page
only when the user click on a button)
9
10. What JavaScript Can do For us?
• Animated/dynamic drop-down menus
• Displaying clock, date, and time
• Get and set cookies, ask questions to the
visitor, show messages
10
22. Variables and Datatypes
Declaring variables
• Variable is a name given to memory location to
store data.
• The stored data changes during the execution of
the program.
22
25. Variables and Datatypes
There are eight basic data types in JavaScript.
Data Types Description Example
String represents textual data 'hello', "hello world!" etc
Number an integer or a floating-point number 3, 3.234, 3e-2 etc.
BigInt an integer with arbitrary precision
900719925124740999n ,
1n etc.
Boolean Any of two values: true or false true and false
undefined a data type whose variable is not initialized let a;
null denotes a null value let a = null;
Symbol
data type whose instances are unique and
immutable
let value = Symbol('hello');
Object key-value pairs of collection of data let student = { };
25
26. Variables and Datatypes
<html> <body> <h2>JavaScript Variables</h2>
<p id="demo"></p>
<script>
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
document.getElementById("demo").innerHTML =
"The total is: " + total;
</script> </body> </html>
26
30. Life span of variable
• Life span of varibale means how long a varibale
retains a given value during the execution of the
program.
• Two types of variables
» Local variable
» Global variable
30
32. • In javascript there is no need to specify the
datatypes of the variables.
• The data types are decided automatically during
script execution.
Example
(i) var answer= 42
32
33. Example
(i) var answer= 42
• This assigns an integer data value to the variable answer.
(ii) var name = "Ramu"
• This assigns a string data to the variable name.
(iii) var b = 2.48
• This assigns a floating point data to the variable b.
33
34. Literals
• Literals are fixed values that does not ch-ange
during the script execution.
• The following types of literals are used in
javascript
34
35. Numbers It can be either integer or float
Boolean It can be true or false
String It is made up of character within double
quotes
Null It contains no value
Undefined A value not assigned to any variable
35
36. OPERATORS
• An operator is a symbol which represents an
operation that can be performed on data.
• There are six operators available in JavaScript
36
41. Control Structures
• Control Structures are used to transfer
JavaScript program control from one statement to
any other statement.
• The different control statements are
41
43. Conditional Statements
• This is where the flow of the execution in a
program is decided.
• Conditional Statements decide the next step based
of the result.
43
49. Different types of Conditional Statements :
• if (condition) {
//code block to be executed
if condition is satisfied
}
• if (condition)
{
// code to be executed of
condition is true
}
else {
// code to be executed of
condition is false
}
49
51. Different types of Conditional Statements :
switch (expression) {
case LABEL-1:
//code block to be executed
Break;
case LABEL-2:
//code block to be executed
Break;
….
case LABEL-N:
//code block to be executed
Break;
default:
//default code to be executed if none of the above case is executed
} 51
53. Different types of Iterative Statement
• while (condition) {
//code block to be
executed if condition is
satisfied
}
• while
{
//code block to be
executed when
condition is satisfied
} (condition)
53
65. JavaScript Function
• Suppose you need to create a program to
create a circle and color it.
• You can create two functions to solve this
problem:
1. a function to draw the circle
2. a function to color the circle
65
66. JavaScript Function
• Dividing a complex problem into smaller
chunks makes your program easy to
understand and reusable.
66
67. JavaScript Function
• JavaScript also has a huge number of inbuilt
functions.
• For example, Math.sqrt() is a function to
calculate the square root of a number.
67
73. Function Parameters - Example
// program to print the text
// declaring a function
function greet(name) {
console.log("Hello " + name + ":)");
}
// variable name can be different
let name = prompt("Enter a name: ");
// calling function
greet(name);
73
77. Function Return
• The return statement can be used to return the value
to a function call.
• The return statement denotes that the function has
ended. Any code after return is not executed.
77
80. Benefits of Using a Function
• Function makes the code reusable. It can declare it
once and use it multiple times.
• Function makes the program easier as each small task
is divided into a function.
• Function increases readability.
80
84. Math Objects
• The Math class allows one to access common
mathematic functions and common values quickly in
one place.
• This static class contains methods such as max(), min(),
pow(), sqrt(), and exp()
84
85. Math
• Trigonometric functions such as sin(), cos(), and
arctan().
• Many mathematical constants are defined such as PI,
E, SQRT2, and some others
85
86. Math Object
• Unlike other objects, the Math object
has no constructor.
• The Math object is static.
• All methods and properties can be used
without creating a Math object first.
86
87. Math Properties (Constants)
• The syntax for any Math property is : Math.property
• JavaScript provides 8 mathematical constants that can
be accessed as Math properties:
87
88. Math Properties (Constants)
• Math.E // returns Euler's number
• Math.PI // returns PI
• Math.SQRT2 // returns the square root of 2
• Math.SQRT1_2 // returns the square root of 1/2
• Math.LN2 // returns the natural logarithm of 2
• Math.LN10 // returns the natural logarithm of 10
• Math.LOG2E // returns base 2 logarithm of E
• Math.LOG10E // returns base 10 logarithm of E
88
89. Math Methods
• The syntax for Math any methods is :
Math.method.(number)
• Example :
Math.sqrt(4); // square root of 4 is 2.
Math.random(); // random number between 0 and 1
89
90. Math Methods - Number to Integer
• There are 4 common methods to round a number to
an integer:
90
Method Description
Math.round(x) Returns x rounded to its nearest integer
Math.ceil(x) Returns x rounded up to its nearest integer
Math.floor(x) Returns x rounded down to its nearest integer
Math.trunc(x) Returns the integer part of x (new in ES6)
91. Arrays
• An array is an object that can store multiple values at
once.
• For example,
const words = ['hello', 'world', 'welcome'];
91
96. Function in Arrays
Method Description
concat() joins two or more arrays and returns a result
indexOf() searches an element of an array and returns its position
find() returns the first value of an array element that passes a test
pop()
removes the last element of an array and returns the
removed element
shift()
removes the first element of an array and returns the
removed element
96
97. Function in Arrays
Method Description
sort() sorts the elements alphabetically in strings and in ascending order
slice() selects the part of an array and returns the new array
splice() removes or replaces existing elements and/or adds new elements
push()
aads a new element to the end of an array and returns the new
length of an array
unshift()
adds a new element to the beginning of an array and returns the
new length of an array
97
105. String
• JavaScript string is a primitive data type that is used
to work with texts.
For example,
const name = 'John';
105
106. Create JavaScript Strings
• Strings are created by surrounding them with quotes.
There are three ways you can use quotes.
•Single quotes: 'Hello'
•Double quotes: "Hello"
•Backticks: `Hello`
106
107. JavaScript String Objects
• create strings using the new keyword.
• For example,
const a = 'hello';
(OR)
const b = new String('hello');
107
109. String Methods
Method Description
charAt(index) returns the character at the specified index
concat() joins two or more strings
replace() replaces a string with another string
split() converts the string to an array of strings
substr(start,
length)
returns a part of a string
109
111. String Methods
Method Description
trim() removes whitespace from the strings
includes()
searches for a string and returns a
boolean value
search()
searches for a string and returns a
position of a match
111
113. Date Object
• The Date class is yet another helpful included object
you should be aware of.
• It allows you to quickly calculate the current date or
create date objects for particular dates.
• To display today’s date as a string, we would simply
create a new object and use the toString() method.
113
114. Date Object
• var d = new Date();
• // This outputs Today is Mon Nov 12 2012 15:40:19
GMT-0700
• alert ("Today is "+ d.toString());
114
115. DOM - Document Object Model
• JavaScript is almost always used to interact with the
HTML document in which it is contained.
• This is accomplished through a programming interface
(API) called the Document Object Model.
115
116. DOM - Document Object Model
• The DOM document object is the root JavaScript
object representing the entire HTML document.
• It contains some properties and methods that we will
use extensively in our development and is globally
accessible as document.
• // specify the doctype, for example html
var a = document.doctype.name;
116
118. DOM Nodes
• In the DOM, each element within the HTML document
is called a node.
• If the DOM is a tree, then each node is an individual
branch.
118
119. DOM Nodes
• There are:
element nodes,
text nodes, and
attribute nodes
• All nodes in the DOM share a common set of
properties and methods.
119
120. DOM - Document Object Model
Method Description
createAttribute() Creates an attribute node
createElement() Creates an element node
createTextNode() Create a text node
getElementById(id)
Returns the element node whose id attribute matches
the passed id parameter.
getElementsByTagName(name)
Returns a nodeList of elements whose tag name
matches the passed name parameter.
120
122. Element node Object
122
Property Description
className The current value for the class attribute of this HTML element.
id The current value for the id of this element.
innerHTML
• Represents all the things inside of the tags.
• This can be read or written to and is the primary way which we
update particular div's using JS.
style
The style attribute of an element. We can read and modify this
property.
tagName The tag name for the element.
123. Modifying a DOM element
123
• The document.write() method is used to create output
to the HTML page from JavaScript.
• The modern JavaScript programmer will want to write
to the HTML page, but in a particular location, not
always at the bottom.
124. Modifying a DOM element
124
• Using the DOM document and HTML DOM element
objects, we can do exactly that using the innerHTML
property.
125. Changing an element’s style
125
• We can add or remove any style using the style or
className property of the Element node.
• Its usage is shown below to change a node’s
background color and add a three-pixel border.
126. Changing an element’s style
126
• var commentTag = document.getElementById("specificTag");
• commentTag.style.backgroundColour = "#FFFF00";
• commentTag.style.borderWidth="3px";
127. JavaScript Events
127
• An event is an action that can be
detected by JavaScript.
• We say then that an event is triggered
and then it can be caught by
JavaScript functions, which then do
something in response.
129. Event Types
129
• There are several classes of event,
1. Mouse Events
2. Keyboard Events
3. Form Events
4. Frame Events
130. Mouse events
130
Event Description
onclick The mouse was clicked on an element
ondblclick The mouse was double clicked on an element
onmousedown The mouse was pressed down over an element
onmouseup The mouse was released over an element
onmouseover The mouse was moved (not clicked) over an element
onmouseout The mouse was moved off of an element
onmousemove The mouse was moved while over an element
136. Keyboard events
136
Event Description
Onkeydown The user is pressing a key (this happens first)
Onkeypress The user presses a key (this happens after onkeydown)
Onkeyup The user releases a key that was down (this happens last)
137. Keyboard events - Example
137
• The following example code, submit a form in both
cases, manually button click and Enter key press on
Keyboard.
138. Keyboard events - Example
138
• Get the element of the input field.
• Execute the keyup function with addEventListener when the user
releases a key on the keyboard.
• Check the number of the pressed key using JavaScript keyCode
property.
• If keyCode is 13, trigger button element with click() event.
141. Form Events
141
Event Description
onblur
A form element has lost focus (that is, control has moved to a
different element, perhaps due to a click or Tab key press.
onchange
Some <input>, <textarea> or <select> field had their value
change. This could mean the user typed something, or selected a
new choice.
onfocus
Complementing the onblur event, this is triggered when an
element gets focus (the user clicks in the field or tabs to it)
onreset
HTML forms have the ability to be reset. This event is triggered
when that happens.
onselect
When the users selects some text. This is often used to try and
prevent copy/paste.
onsubmit
When the form is submitted this event is triggered. We can do some
pre-validation when the user submits the form in JavaScript before
sending the data on to the server.
143. Frame Events
143
• Frame events are the events related to the browser frame that
contains your web page.
• The most important event is the onload event, which tells us an
object is loaded and therefore ready to work with.
144. Frame Events
144
Event Description
onabort An object was stopped from loading
onerror An object or image did not properly load
onload When a document or object has been loaded
onresize The document view was resized
onscroll The document view was scrolled
onunload The document has unloaded
151. MCQ’s QUESTIONS
151
QUESTION 2
HOTSPOT
You are planning to use the Math object in a JavaScript
application. You write the following code to evaluate various
Math functions:
152. MCQ’s QUESTIONS
152
What are the final values for the three variables? To answer,
select the appropriate values in the answer area.