Module 5
Module 5
Java script is a client and server-side object-based scripting language that is used to make
interactive web pages.
Features of JavaScript:
1. Imperative and structured: implies that javascript supports all the syntaxes of the
structured programming language C, such as if statement, loops and the switch
statements. Semicolon is not necessary to terminate a statement.
2. Dynamic text: JavaScript supports dynamic typing, which means the type of a
variable is defined according to the value stored in it.
It is an object-based scripting language, which provides some built-in objects, such as
strings, math and date objects.
3. Functional: it does not support classes, instead using classes, objects are created from
the constructor functions
4. Prototype-based: javascript is a Prototype-based language, which means java script
uses prototypes instead of classes for inheritance. There are several Built-in objects
that represent a constructor functions such as Array(), Date(), Number(), String()
5. Platform-independent: user can write script once and run it anywhere and anytime
Example:
<!DOCTYPE html>
<html>
<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
Example :
<!DOCTYPE html>
<html>
<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script src="app.js"></script>
</body>
</html>
app.js:
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
Identifiers: it refers to the names given to all the components, such as variables, and
methods, of a javascript program. Rules and guidelines for identifiers as follows
Identifiers must starts with a letter, dollar sign($), or underscore(_)
It cannot start with a number.
It can contain any combination of letters, a dollar sign, and numbers after the first
character.
It can be any length.
Identifiers are case-sensitive.
It cannot contain reserved words or keywords.
Reserved words: these are the words whose meanings are already defined to the javascript
interpreter.
2. Variables: in javascript, data can be temporarily stored in a variables, which are the
named locations in the memory.
Syntax: var is KEYWORD and variable_name represents the name of the variables
Example: Var variable_name; or
Var var1, var2; or
Var var=value
{ Var vname; vname=value;}
3. Operators: Operators are used to perform operations on variables and values.
Operators work on one or more operands i.e, an operator can take the values of more
than one operand.
List of operators:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Conditional operators
Arithmetic operators
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x–3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
Comparison operators
== Equal to x == y
!= Not equal x != y
Logical operators
user can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)
conditional operators
?: -- it returns the second operand if the first operand is true. If the first operand is false, it
returns the third operand
1. Selection statements
o if statements: It evaluates a Boolean expression and enables the program to
enter a block of code if the expression evaluates to true.
if(condition)
{
statement 1; //executes when condition is true.
}
Example :
let age=20;
if(age>=18){
console.log(“You are an adult”);
}
o if else
The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true.
}
else{
statement 2; //executes when condition is false.
}
Example :
let age=16;
if(age>=18){
console.log(“You are an adult”);
}else{
console.log(“You are a minor”);
}
o switch statement
Switch statements are like if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the
variable which is being switched.
Syntax:
switch (expression) {
case value1:
break;
case value2:
break;
default:
Example :
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Another day");
2. Loop statements
o While loop
The while loop is also used to iterate over the number of statements multiple times.
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.
initialization
while(condition){
//looping statements
updation
}
Example :
let i=0;
while(i<=10)
{
console.log(i);
i++;
}
o do while loop
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iterations is not known and we have to execute the loop at
least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
initialization
do{
//statements
updation
} while (condition);
Example :
let i=0;
do{
console.log(“The number is”,i);
i++;
}while(i<=10);
let i=0;
do{
console.log(“The number is”,i);
i++;
}while(i<=0);
o for loop
It enables us to initialize the loop variable, check the condition, and increment/decrement in a
single line of code. We use the for loop only when we exactly know the number of times, we
want to execute the block of code.
for(initialization;condition; increment/decrement) {
//block of statements
}
Example:
for (let i=0; i<5; i++){
console.log(“Hello World”,i);
}
3. Jump statements Jump statements are used to transfer the control of the program to
the specific statements.
o break statement: the break statement is used to break the current flow of the
program and transfer the control to the next statement outside a loop or switch
statement. However, it breaks only the inner loop in the case of the nested
loop.
Example:
if (i==3) {
break;
console.log(i);
let i=1;
while(i<=5){
if(i==4)
break;
}
console.log(i);
i++;
o continue statement: the continue statement doesn't break the loop, whereas, it
skips the specific part of the loop and jumps to the next iteration of the loop
immediately.
Example :
if (i==5){
continue;
document.write(i+”<br/>”);
5. Popup boxes:
popup boxes are used to display the message or notification to the user.
There are three types of pop-up boxes in JavaScript namely Alert Box, Confirm
Box and Prompt Box.
Alert Box: It is used when a warning message is needed to be produced. When the alert
box is displayed to the user, the user needs to press ok and proceed.
Syntax:
alert("your Alert here")
Example:
<!DOCTYPE html>
<html>
<head>
<title>Alert Box</title>
</head>
<body>
<center>
<h3>Alert Box</h3>
<button onclick="Alert()">Click here for alert box</button>
<!-- Alert box function -->
<script>
function Alert() {
alert("displays an alert message"+" and also error message");
}
</script>
</center>
</body>
</html>
Prompt Box: It is a type of pop up box which is used to get the user input for further use.
After entering the required details user must click ok to proceed next stage else by pressing
the cancel button user returns the null value.
Syntax:
prompt("your Prompt here")
Example:
<!DOCTYPE html>
<html>
<head>
<title>Prompt Box</title>
</head>
<body>
<h3>Prompt Box used to input a value from user</h3>
<input type="button" onclick="Prompt();" value="Click here for Prompt box"/>
<!-- Prompt box function -->
<script>
function Prompt() {
var x = prompt("Enter your mail here :");
document.write("Your ID : " + x);
}
</script>
</body>
</html>
Confirm Box: It is a type of pop-up box that is used to get authorization or permission
from the user. The user must press the ok or cancel button to proceed.
Syntax:
confirm("your query here")
Example:
<!DOCTYPE html>
<html>
<head>
<title>Pop-up Box type | Confirm Box</title>
</head>
<body>
<h3>Confirm Box is used to get authorization or permission from the user.</h3>
<button onclick="Confirm()">Click here for Confirm box</button>
<p id="a"></p>
<!-- Confirm box function -->
<script>
function Confirm() {
var x;
if (confirm("Press a button") == true)
{
x = "OK pressed";
} else {
x = "Cancel";
}
document.getElementById("a").innerHTML = x;
}
</script>
</body>
</html>
JAVASCRIPT FUNCTIONS
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).
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code
after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
Example
function myFunction(a, b)
{
return a*b; //Function returns the product of a and b
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>
Function scope
A scope refers to an area which a function and its variables are accessible.
Two categories of scope of a function
1 Global- specifies that a function can be called or accessed from
anywhere in a program
2 Local- specifies that a function can be called or accessed only
within its parent function
Timing Events
setTimeout(function, milliseconds)
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Timing</h2>
<p>Click "Try it". Wait 3 seconds. The page will alert "Hello".</p>
<script>
function myFunction() {
alert("Hello");
</script>
</body>
</html>
setInterval(function, milliseconds)
Example :
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Timing</h2>
<script>
setInterval(myTimer, 5000);
function myTimer() {
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
</script></body></html>
Objects in javascript:
The JS language is based on objects. In JS we can create an object in two ways either
by creating a direct instance or by creating an object using a function template.
A direct instance of an object is created by using the new keyword.
Syntax: let Obj=new object();
Properties and methods can be added to an object by using a period(.) followed by a
property or method name, as
Obj.name=”aaa”;
Obj.age=20;
Obj.getvalue();
All event objects in the HTML DOM are based on the Event Object.
Explanation :
Syntax :
let obj = new Object();
The new keyword can be used to create an instance of an object. This creates an empty
object in JavaScript using the built-in Object constructor.
Adding Properties and Methods:
You can use the dot (.) notation to add properties or methods to the object.
obj.name = "John";
obj.age = 25;
obj.getValue = function () {
return this.name + " is " + this.age + " years old.";
};
console.log(obj.getValue()); // Output: "John is 25 years old."
All event objects (like MouseEvent and KeyboardEvent) has access to the Event Object's
properties and methods.
Javascript objects
Event Description
onmouseout The user moves the mouse away from an HTML element
Keyboard Events
Mouse Events