UNIT-2 - Ost
UNIT-2 - Ost
Internal JS: We can add JavaScript directly to our HTML file by writing the
code inside the <script> tag. The <script> tag can either be placed inside
the <head> or the <body> tag according to the requirement.
Syntax:
<script>
// JavaScript Code
</script>
DATA TYPES:
an integer or a floating-point
Number 3, 3.234, 3e-2 etc.
number
900719925124740999n , 1n
BigInt an integer with arbitrary precision
etc.
VARIABLES:
Variables are containers for storing data (storing data values).
4 Ways to Declare a JavaScript Variable:
Using var
Using let
Using const
Using nothing
OPERATORS:
ARITHMEIC OPERATOR:
+ (Addition):
‘+’ operator performs addition on two operands.
Example:
Y = 5 + 5 gives Y = 10
– (Subtraction):
‘-‘ operator performs subtraction on two operands.
Example:
Y = 5 - 3 gives Y = 2
* (Multiplication):
‘*’ operator performs multiplication on two operands.
Example:
Y = 5 * 5 gives Y = 25
/ (Division):
‘/’ operator performs division on two operands (divide the numerator by
the denominator).
Example:
Y = 5 / 5 gives Y = 1
% (Modulus):
‘%’ operator gives remainder of an integer division.
Example:
A % B means remainder (A/B)
Y = 5 % 4 gives Y = 1
ASSIGNMENT OPERATOR:
= (Assignment Operator):
Assigns right operand value to left operand.
Example:
If A = 10 and Y = A then Y = 10
+= (Add and Assignment Operator) :
Sums up left and right operand values and then assign the result to the
left operand.
Example:
Y += 1 gives Y = Y + 1
– = (Subtract and Assignment Operator) :
It subtract right side value from left side value and then assign the result
to the left operand.
Example:
Y -= 1 gives Y = Y - 1
similarly, there are *= (Multiply and Assignment), /= (Divide and
Assignment), %= (Modules and Assignment)
Example:
Y *= A is equivalent to Y = Y * A
Y /= A is equivalent to Y = Y / A
Y %= A is equivalent to Y = Y % A
COMPARISON OPERATOR:
There are various Comparison Operators in JavaScript –
==:
Compares the equality of two operands. If equal then the condition is true
otherwise false.
Example :
Y = 5 and X = 6
Y = = X is false.
===:
this operator compares equality of two operands with type.If equal(type and
value both) then condition is true otherwise false.
Example:
given X = 10 then X = = = "10" is false.
X = = = 10 is true.
!= (Not Equal):
Compares inequality of two operands. True if operands are not equal.
Example:
given X = 10 then X ! = 11 is true.
> (Greater than):
this operator checks whether the left side value is greater than the right
side value. If yes then it returns true otherwise it returns false.
Example:
given X = 10 then X > 11 is false.
< (Less than):
this operator checks whether the left side value is less than right side
value. If yes then it returns true otherwise it returns false.
Example:
given X = 10 then X < 11 is true.
> = (Greater than or Equal to):
this operator checks whether the left side operand is greater than or equal
to the right side operand. If yes then it returns true otherwise it returns
false.
Example:
given X = 10 then X > = 11 is false.
<= (Less than or Equal to):
this operator checks whether the left side operand value is less than or
equal to the right side operand value. If yes then it returns true otherwise
it returns false.
Example:
given X = 10 then X < = 10 is true.
LOGICAL OPERATOR:
There are various Logical Operators in JavaScript –
Example:
Y = 5 and X = 6
Y && X is true.
|| (Logical OR):
It checks whether any one of the two operands is non-zero (0, false,
undefined, null, or “” is considered as zero). Thus || returns true if either
operand is true and if both are false it returns false.
Example:
Y = 5 and X = 0
Y || X is true.
! (Logical NOT):
It reverses the boolean result of the operand (or condition).
Example:
Y = 5 and X = 0
!(Y || X) is false.
Ternary Operator:
: ? Operator:
It is like the short form of the if-else condition.
Syntax:
Y= ?A:B
where A and B are values and if condition is true then Y = A otherwise Y
= B.
Example:
Y = (6>5) ? 6 : 5
therefore Y = 6
TYPEOF OPERATOR:
It returns the type of a variable.
Syntax:
typeof variable;
Example:
<html>
<head>
</head>
<body>
<script type="text/javascript">
var a = 17;
var b = "GeeksforGeeks";
var c = "";
var d = null;
document.write("<br>");
document.write("<br>");
document.write("<br>");
document.write("<br>");
document.write("<br>");
</script>
</body>
</html>
Output:
Type of a = number
Type of b = string
Type of c = string
Type of d = object
Type of e = undefined
DIALOG BOXES:
JavaScript supports three important types of dialog boxes. These dialog boxes
can be used to raise and alert, or to get confirmation on any input or to have a
kind of input from the users. Here we will discuss each dialog box one by one.
ALERT DIALOG BOXES:
An alert dialog box is mostly used to give a warning message to the
users. For example, if one input field requires to enter some text but the
user does not provide any input, then as a part of validation, you can use
an alert box to give a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert
box gives only one button "OK" to select and proceed.
EXAMPLE:
<html>
<head>
<script type = "text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();" />
</form>
</body>
</html>
OUTPUT:
CONFIRMATION DIALOG BOXES:
A confirmation dialog box is mostly used to take user's consent on any option.
It displays a dialog box with two buttons: OK and Cancel.
If the user clicks on the OK button, the window method confirm() will return
true. If the user clicks on the Cancel button, then confirm() returns false
EXAMPLE:
<html>
<head>
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Do you want to continue ?");
if( retVal == true ) {
document.write ("User wants to continue!");
return true;
} else {
document.write ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getConfirmation();"
/>
</form>
</body>
</html>
OUTPUT:
PROMPT DIALOG BOXES:
The prompt dialog box is very useful when you want to pop-up a text box
to get user input. Thus, it enables you to interact with the user. The user
needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes
two parameters: (i) a label which you want to display in the text box and
(ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the
OK button, the window method prompt() will return the entered value
from the text box. If the user clicks the Cancel button, the window
method prompt() returns null.
EXAMPLE:
<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>
OUTPUT:
CONTROL STATEMENTS:
Control Statements in Java is one of the fundamentals required for Java
Programming. It allows the smooth flow of a program. Following pointers will
be covered in this article:
Statements that determine which statement to execute and when are known
as decision-making statements. The flow of the execution of the program is
controlled by the control flow statement.
There are four decision-making statements available in java.
SIMPLE IF STATEMENTS:
SYNTAX:
1 if (condition) {
2 Statement 1; //executed if condition is true
3 }
4 Statement 2; //executed irrespective of the condition
OUTPUT:
If statement!
Hello World!
IF ELSE STATEMENTS:
EXAMPLE:
OUTPUT:
a is less than 10
Hello World!
NESTED IF STATEMENTS:
1 if (condition1) {
2 Statement 1; //executed if first condition is true
3 if (condition2) {
4 Statement 2; //executed if second condition is true
5 }
6 else {
7 Statement 3; //executed if second condition is false
8 }
9 }
EXAMPLE:
OUTPUT:
s is an even number and greater than 10!
Hello World!
SWITCH STATEMENTS:
EXAMPLE:
OUTPUT:
Flute
LOOPING STATEMENTS:
WHILE: Known as the most common loop, the while loop evaluates a certain
condition. If the condition is true, the code is executed. This process is
continued until the specified condition turns out to be false.
The condition to be specified in the while loop must be a Boolean expression.
An error will be generated if the type used is int or a string.
SYNTAX:
1 while (condition)
2 {
3 statementOne;
4 }
EXAMPLE:
OUTPUT:
5
7
9
11
13
15
DO WHILE:
The do-while loop is similar to the while loop, the only difference being that the
condition in the do-while loop is evaluated after the execution of the loop body.
This guarantees that the loop is executed at least once.
SYNTAX:
1 do{
2 //code to be executed
3 }while(condition);
EXAMPLE:
20
FOR LOOP:
The for loop in java is used to iterate and evaluate a code multiple times.
When the number of iterations is known by the user, it is recommended to use
the for loop.
SYNTAX:
EXAMPLE:
OUTPUT:
5
6
7
8
9
10
FOR EACH:
The traversal of elements in an array can be done by the for-each loop. The
elements present in the array are returned one by one. It must be noted that
the user does not have to increment the value in the for-each loop.
EXAMPLE:
OUTPUT:
18
25
28
29
30
BRANCHING STATEMENTS:
BREAK STATEMENTS:
The break statement in java is used to terminate a loop and break the current
flow of the program.
EXAMPLE:
OUTPUT:
5
6
7
CONTINUE:
To jump to the next iteration of the loop, we make use of the continue
statement. This statement continues the current flow of the program and skips
a part of the code at the specified condition.
EXAMPLE:
OUTPUT:
6 8 10 12 14
FUNCTIONS:
SYNTAX:
SYNTAX:
function functionname()
FUNCTION CALL():
EXAMPLE:
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
const person2 = {
firstName:"Mary",
lastName: "Doe"
}
OUTPUT:
JavaScript Functions
John Doe
RECURSION:
Recursion is best applied when you need to call the same function repeatedly
with different parameters from within a loop. While it can be used in many
situations, it is most effective for solving problems involving iterative
branching, such as fractal math, sorting, or traversing the nodes of complex or
non-linear data structures.
SYNTAX:
function recurse() {
// function code
recurse();
// function code
}
recurse();
DECLARATION OF ARRAYS:
Javascript Array is a global object which contains a list of elements. It is
similar to other variables where they hold any type of data according to
data type declaration but the difference is Array can hold more than one
item at a time.
SYNTAX:
The array takes a list of items separated by a comma and enclosed in square
brackets.
OUTPUT:
<!DOCTYPE html>
<html>
<body>
<h1>Using array literal syntax</h1>
<script>
var sArray = ["Karthick", "Saideep", "Anusha"];
var nArray = [10, 20, 30, 4];
var dArray = [1.5, 1.8, 5.3];
var bArray = [true, false, false];
var Array = [1, "Saideep", "Anusha", 0];
document.write(sArray);
document.write('</br>');
document.write(nArray);
document.write('</br>');
document.write(dArray);
document.write('</br>');
document.write(bArray);
document.write('</br>');
document.write(Array);
</script>
</body>
</html>
SORTING ARRAY:
You can use the JavaScript sort() method to sort an array. The sort()
method accepts an array as an argument and sorts its values in
ascending order. Arrays are sorted in place which means the original
array is modified. A new array is not created.
You may decide that you want to sort your array in a particular order.
For instance, you may have a list of names that you want to display to
the user in alphabetical order.
Depending on how you want to sort the elements in an array, there are
built-in JavaScript functions that can help. For example, you can use the
sort() function to sort an array in alphabetical order, the reverse()
function to sort an array in reverse order, and the sort() function with a
nested function to create your own custom sorts
SYNTAX:
const values = [1, 2, 8, 9, 3];
values.sort();
SEARCHING ARRAYS:
Each value in the array is called an item, and together they form an indexed
list of values.
There are various Array methods which enable us to search arrays, each of
which returns a different type of data:
We can search the array for a single value, returning that value to
the caller
We can return a given value’s index in the array
We can return a Boolean value indicating presence in an array
We can return a new array with one or more values from the
original
JAVASCRIPT MATH OBJECT:
The JavaScript Math object allows you to perform mathematical tasks on
numbers.
EXAMPLE:
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
Math.pow(8, 2);
Math.sqrt(64);
Math.abs(-4.7);
Math.min(0, 150, 30, 20, -8, -200);
Math.max(0, 150, 30, 20, -8, -200);
STRING OBJECTS:
The string object provide several properties and methods to work around
strings. The string objects can be created using new keyword. For example:
var y = “Hello”;
In the above example, the variable x is a string object whereas the variable y
is a string literal or regular text string. The string literals can also use all the
methods and properties of the String object.
The difference between String object and string literals is that, the string
literals can be compared with another string literal. For example:
var x = “Hello”;
var y = “Hello”;
if(x === y)
alert(“Equal”);
else
alert(“Not Equal”);
In the above code, the alert(“Equal”) will execute. However let us see the
example with String objects.
if(x === y)
alert(“Equal”);
else
alert(“Not Equal”);
In the above code, the alert(“Not Equal”) will be executed even though the
values that the object holds are the same. This is because the string objects is
an object value and not a string literal and the value might be same but the
type isn’t.