0% found this document useful (0 votes)
46 views25 pages

UNIT-2 - Ost

JavaScript is a lightweight, interpreted programming language best known for its use in web development. It can be used for both client-side development in web browsers and server-side development with frameworks like Node.js. JavaScript has various data types, variables, operators, and functions. It allows adding interactivity to web pages through features like dialog boxes, form validation, and manipulating the DOM.

Uploaded by

Sandy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views25 pages

UNIT-2 - Ost

JavaScript is a lightweight, interpreted programming language best known for its use in web development. It can be used for both client-side development in web browsers and server-side development with frameworks like Node.js. JavaScript has various data types, variables, operators, and functions. It allows adding interactivity to web pages through features like dialog boxes, form validation, and manipulating the DOM.

Uploaded by

Sandy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

INTRODUCTION TO JAVASCRIPT

JavaScript is a lightweight, cross-platform, and interpreted scripting


language. It is well-known for the development of web pages, many non-
browser environments also use it. JavaScript can be used for Client-
side developments as well as Server-side developments. JavaScript
contains a standard library of objects, like Array, Date, and Math, and a core
set of language elements like operators, control structures,
and statements.

Client-side: It supplies objects to control a browser and its Document


Object Model (DOM). Like if client-side extensions allow an application to
place elements on an HTML form and respond to user events such
as mouse clicks, form input, and page navigation. Useful libraries for
the client-side are AngularJS, ReactJS, VueJS and so many others.

Server-side: It supplies objects relevant to running JavaScript on a


server. Like if the server-side extensions allow an application to
communicate with a database, and provide continuity of information from
one invocation to another of the application, or perform file manipulations
on a server. The useful framework which is the most famous these days
is node.js.

JavaScript can be added to your HTML file In two ways:

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.

External JS: We can write JavaScript code in other file having an


extension .js and then link this file inside the <head> tag of the HTML file
in which we want to add this code.

Syntax:
<script>
// JavaScript Code
</script>

DATA TYPES:

There are eight basic data types in JavaScript. They are:


Data
Description Example
Types

String represents textual data 'hello', "hello world!" etc

an integer or a floating-point
Number 3, 3.234, 3e-2 etc.
number

900719925124740999n , 1n
BigInt an integer with arbitrary precision
etc.

Boolean Any of two values: true or false true and false

a data type whose variable is not


undefined let a;
initialized

null denotes a null value let a = null;

data type whose instances are


Symbol let value = Symbol('hello');
unique and immutable

Object key-value pairs of collection of data let student = { };

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:

An operator is capable of manipulating a certain value or operand.


Operators are used to perform specific mathematical and logical computations
on operands. In other words, we can say that an operator operates the
operands. In JavaScript operators are used for compare values, perform
arithmetic operations etc.

There are various operators supported by JavaScript:


Arithmetic Operators
Comparison Operators
Logical Operators
Assignment Operators
Ternary Operators
typeof Operator

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:

There are various Assignment Operators in JavaScript –

= (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 –

&& (Logical AND):


It checks whether two operands are non-zero (0, false, undefined, null or
“” are considered as zero), if yes then return 1 otherwise 0.

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>

<title> GfG typeof example </title>

</head>

<body>
<script type="text/javascript">

var a = 17;

var b = "GeeksforGeeks";

var c = "";

var d = null;

document.write("Type of a = " + (typeof a));

document.write("<br>");

document.write("Type of b = " + (typeof b));

document.write("<br>");

document.write("Type of c = " + (typeof c));

document.write("<br>");

document.write("Type of d = " + (typeof d));

document.write("<br>");

document.write("Type of e = " + (typeof e));

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:

Decision Making Statements


Simple if statement
if-else statement
Nested if statement
Switch statement
Looping statements
While
Do-while
For
For-Each
Branching statements
Break
Continue

DECISION MAKING STATEMENTS:

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.

Moving on with this article on Control Statements in Java

SIMPLE IF STATEMENTS:

The if statement determines whether a code should be executed based on the


specified condition.

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:

In this statement, if the condition specified is true, the if block is executed.


Otherwise, the else block is executed.

EXAMPLE:

1 public class Main


2 {
3 public static void main(String args[])
4 {
5 int a = 15;
6 if (a > 20)
7 System.out.println("a is greater than 10");
8 else
9 System.out.println("a is less than 10");
10 System.out.println("Hello World!");
11 }
12 }
13 }

OUTPUT:
a is less than 10
Hello World!

Moving on with this article on Control Statements in Java

NESTED IF STATEMENTS:

An if present inside an if block is known as a nested if block. It is similar to an


if..else statement, except they are defined inside another if..else statement.
SYNTAX:

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:

1 public class Main


2 {
3 public static void main(String args[])
4 {
5 int s = 18;
6 if (s > 10)
7 {
8 if (s%2==0)
9 System.out.println("s is an even number and greater than 10!");
10 else
11 System.out.println("s is a odd number and greater than 10!");
12 }
13 else
14 {
15 System.out.println("s is less than 10");
16 }
17 System.out.println("Hello World!");
18 }
19 }

OUTPUT:
s is an even number and greater than 10!
Hello World!

SWITCH STATEMENTS:

A switch statement in java is used to execute a single statement from multiple


conditions. The switch statement can be used with short, byte, int, long, enum
types, etc.
1) Certain points must be noted while using the switch statement:
2) One or N number of case values can be specified for a switch expression.
3) Case values that are duplicate are not permissible. A compile-time error is
generated by the compiler if unique values are not used.
4) The case value must be literal or constant. Variables are not permissible.
5) Usage of break statement is made to terminate the statement sequence. It
is optional to use this statement. If this statement is not specified, the next
case is executed.

EXAMPLE:

1 public class Music {


2 public static void main(String[] args)
3 {
4 int instrument = 4;
5 String musicInstrument;
6 // switch statement with int data type
7 switch (instrument) {
8 case 1:
9 musicInstrument = "Guitar";
10 break;
11 case 2:
12 musicInstrument = "Piano";
13 break;
14 case 3:
15 musicInstrument = "Drums";
16 break;
17 case 4:
18 musicInstrument = "Flute";
19 break;
20 case 5:
21 musicInstrument = "Ukelele";
22 break;
23 case 6:
24 musicInstrument = "Violin";
25 break;
26 case 7:
27 musicInstrument = "Trumpet";
28 break;
29 default:
30 musicInstrument = "Invalid";
31 break;
32 }
33 System.out.println(musicInstrument);
34 }
35 }

OUTPUT:

Flute

LOOPING STATEMENTS:

Statements that execute a block of code repeatedly until a specified


condition is met are known as looping statements. Java provides the
user with three types of loops:
Moving on with this article on Control Statements in Java

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:

1 public class whileTest


2 {
3 public static void main(String args[])
4 {
5 int i = 5;
6 while (i <= 15)
7 {
8 System.out.println(i);
9 i = i+2;
10 }
11 }
12

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:

1 public class Main


2 {
3 public static void main(String args[])
4 {
5 int i = 20;
6 do
7 {
8 System.out.println(i);
9 i = i+1;
10 } while (i <= 20);
11 }
12 }
OUTPUT:

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:

1 for (initialization; condition; increment/decrement)


2 {
3 statement;
4 }

EXAMPLE:

1 public class forLoop


2 {
3 public static void main(String args[])
4 {
5 for (int i = 1; i <= 10; i++)
6 System.out.println(i);
7 }
8 }

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:

1 public class foreachLoop{


2 public static void main(String args[]){
3 int s[] = {18,25,28,29,30};
4 for (int i : s) {
5 System.out.println(i);
6 }
7 }
8 }

OUTPUT:
18
25
28
29
30

BRANCHING STATEMENTS:

Branching statements in java are used to jump from a statement to another


statement, thereby the transferring the flow of execution.

Moving on with this article on Control Statements in Java

BREAK STATEMENTS:

The break statement in java is used to terminate a loop and break the current
flow of the program.
EXAMPLE:

1 public class Test


2 {
3 public static void main(String args[])
4 {
5 for (int i = 5; i < 10; i++)
6 {
7 if (i == 8)
8 break;
9 System.out.println(i);
10 }
11 }
12 }

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:

1 public class Main


2 {
3 public static void main(String args[])
4 {
5 for (int k = 5; k < 15; k++)
6 {
7 // Odd numbers are skipped
8 if (k%2 != 0)
9 continue;
10 // Even numbers are printed
11 System.out.print(k + " ");
12 }
13 }
14 }

OUTPUT:
6 8 10 12 14

FUNCTIONS:

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it)

SYNTAX:

function myFunction(p1, p2) {


return p1 * p2; // The function returns the product of p1 and p2
}

CREATING A FUNCTION IN JAVASCRIPT:

1. Use the keyword function followed by the name of the function.


2. After the function name, open and close parentheses.
3. After parenthesis, open and close curly braces.
4. Within curly braces, write your lines of code.

SYNTAX:

function functionname()

lines of code to be executed

FUNCTION CALL():

The call() method is a predefined JavaScript method.


It can be used to invoke (call) a method with an owner object as an
argument (parameter).

With call(), an object can use a method belonging to another object.

EXAMPLE:
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
const person2 = {
firstName:"Mary",
lastName: "Doe"
}

// This will return "John Doe":


person.fullName.call(person1);

OUTPUT:

JavaScript Functions

This example calls the fullName method of person, using it on person1:

John Doe

RECURSION:

Recursion is a technique for iterating over an operation by having a function


call itself repeatedly until it arrives at a result. Most loops can be rewritten in a
recursive style, and in some functional languages this approach to looping is
the default.

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.

Javascript allows a declaration of an array in many ways. Most


important and common among those are ‘Using array constructor’ and
‘Using literal notation’.

SYNTAX:

The array takes a list of items separated by a comma and enclosed in square
brackets.

var <array_name> = [element0, element1, element2, element3, ….. ];

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.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

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 x = new String(“Hello”);


The string literals are created by assigning the value to a variable. 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.

var x = new String(“Hello”);

var y = new String(“Hello”);

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.

You might also like