0% found this document useful (0 votes)
5 views53 pages

Module 2 Javascript (1)

The document provides an extensive overview of JavaScript, covering its introduction, features, applications, and integration with HTML. It discusses client-side and server-side scripting, the use of the <script> tag, variable declaration, data types, operators, and the differences between var, let, and const. Additionally, it includes examples and explanations of JavaScript's capabilities in web development.

Uploaded by

sharanyavp
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)
5 views53 pages

Module 2 Javascript (1)

The document provides an extensive overview of JavaScript, covering its introduction, features, applications, and integration with HTML. It discusses client-side and server-side scripting, the use of the <script> tag, variable declaration, data types, operators, and the differences between var, let, and const. Additionally, it includes examples and explanations of JavaScript's capabilities in web development.

Uploaded by

sharanyavp
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/ 53

1

Unit II
Javascript: Introduction, Client side programming, script tag, comments, variables. Including JavaScript in
HTML: head, body, external. Data types. Operators: Arithmetic, Assignment, Relational, Logical.
Conditional Statements, Loops, break and continue. Output functions: write,writeln, popup boxes: prompt,
alert, confirm. Functions: Built-in Global Functions: alert(), prompt(),confirm(), isNan(), Number(),
parseInt(). User Defined Functions, Calling Functions with Timer,Events Familiarization: onLoad, onClick,
onBlur, onSubmit, onChange, Document Object Model(Concept). Objects: String, Array, Date.

JavaScript (js) is a light-weight object-oriented programming language which is used by several websites
for scripting the webpages. It is an interpreted, full-fledged programming language that enables dynamic
interactivity on websites when applied to an HTML document. It was introduced in the year 1995 for adding
programs to the webpages in the Netscape Navigator browser. Since then, it has been adopted by all other
graphical web browsers. With JavaScript, users can build modern web applications to interact directly
without reloading the page every time. The traditional website uses js to provide several forms of
interactivity and simplicity.
 JavaScript was invented by Brendan Eich in 1995.
 It was developed for Netscape 2, and became the ECMA-262 standard in 1997.
 After Netscape handed JavaScript over to ECMA, the Mozilla foundation continued to develop
JavaScript for the Firefox browser. Mozilla's latest version was 1.8.5. (Identical to ES5).
 Internet Explorer (IE4) was the first browser to support ECMA-262 Edition 1 (ES1).
 ECMAScript 2023, the 14th and current version, was released in June 2023.
Features of JavaScript
1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a structured
programming language.

3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the
operation).

4. JavaScript is an object-oriented programming language that uses prototypes rather than using classes
for inheritance.

5. It is a light-weighted and interpreted language.


6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.
2

Application of JavaScript
 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and
prompt dialog box),
 Displaying clocks etc.

Client-Side Scripting Server-side Scripting


It is executed on the client side i.e. Front-end. It is executed on the server side i.e. Back-end
It is visible to the user It is not visible to the user
Useful in various frontend Operations Useful in various backend operations
It can be used to collect the input given by the It can be used to process the input given by the user
user
It is not preferred for performing complex It is preferred for performing complex computations
computations and transactions and transactions
It is generally less secure It is generally more secure
It usually depends on the browser and its In this any server-side technology can be used and it
version. does not depend on the client.
No need of interaction with the server. It is all about interacting with the servers.
It reduces load on processing unit of the server. It surge the processing load on the server.

HTML, CSS and JavaScript are used for Client- Node.js, PHP, Python and Java are used for Server-
side programming side programming

<script> Tag
 The <script> tag is used to embed a client-side script (JavaScript).
 The <script> element either contains scripting statements, or it points to an external script file
through the src attribute.
 Common uses for JavaScript are image manipulation, form validation, and dynamic changes of
content.
Syntax of script tag
<script>
//code to be executed
</script>
3

Attributes of HTML script tag


Attribute Description
src It specifies the URL of an external script file.
type It specifies the media type of the script.
async It is a boolean value which specifies that the script is executed asynchronously.
defer It is a boolean value which is used to indicate that script is executed after document has been
parsed.

Usage of script tag


1. to embed script code
2. to link script file
Embed script code
The script tag can be used within <body> or <head> tag to embed the scripting code. Let's see the example
to have script tag within HTML body.
<script type="text/javascript">
document.write("JavaScript ")
</script>

Link script file


 We can create external JavaScript file and embed it in many html page.
 It provides code re usability because single JavaScript file can be used in several html pages.
 An external JavaScript file must be saved by .js extension. It is recommended to embed all
JavaScript files into a single file. It increases the speed of the webpage.
 The script tag can be used to link external script file by src attribute. It must be used within the
<head> tag only.
<script type="text/javascript" src="message.js" />
message.js
function msg(){
alert("Hello");
}
index.html
<html>
<head>
<script type="text/javascript" src="message.js"></script> </head> <body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
4

</form>
</body>
</html>

JavaScript Variables

In programming, a variable is a container (storage area) to hold data. For example,

let num = 5;

Here, num is a variable. It's storing 5.

JavaScript Declare Variables

In JavaScript, we use either var or let keyword to declare variables. For example,

var x;

let y;

Here, x and y are variables.

JavaScript var Vs let

Both var and let are used to declare variables.

var let
var is used in the older versions of let is the new way of declaring variables starting ES6
JavaScript (ES2015).
var is function let is block scoped
For example, var x; For example, let y;
Note: It is recommended we use let instead of var. However, there are a few browsers that do not support let.
JavaScript Initialize Variables
We use the assignment operator = to assign a value to a variable.
let x;
x = 5;
Here, 5 is assigned to variable x.

You can also initialize variables during its declaration.

let x = 5;

let y = 6;

In JavaScript, it's possible to declare variables in a single statement.

let x = 5, y = 6, z = 7;
5

Rules for Naming JavaScript Variables

The rules for naming variables are:


 Variable names must start with either a letter, an underscore _, or the dollar sign $. For example,
//valid
let a = 'hello';
let _a = 'hello';
let $a = 'hello';
 Variable names cannot start with numbers. For example,
//invalid
Let 1a = 'hello'; // this gives an error
 JavaScript is case-sensitive. So y and Y are different variables. For example,
let y = "hi";
let Y = 5;
console.log(y); // hi
console.log(Y); // 5
 Keywords cannot be used as variable names. For example,
//invalid
let new = 5; // Error! new is a keyword
JavaScript Let

 The let keyword was introduced in ES6 (2015)


 Variables defined with let cannot be Redeclared
 Variables defined with let must be Declared before use
 Variables defined with let have Block Scope
 Variables defined with let can not be redeclared.
With let you can not do this:

let x = "John Doe";


let x = 0;
With var you can:

var x = "John Doe";


var x = 0;

JavaScript Constants
The const keyword was also introduced in the ES6(ES2015) version to create constants. For example,
const x = 5;
Once a constant is initialized, we cannot change its value.
6

const x = 5;
x = 10; // Error! constant cannot be changed.
console.log(x)
Simply, a constant is a type of variable whose value cannot be changed.
Also, you cannot declare a constant without initializing it. For example,
const x; // Error! Missing initializer in const declaration.
x = 5;
console.log(x)
JavaScript in HTML Document
JavaScript code is inserted between <script> and </script> tags when used in an HTML
document. Scripts can be placed inside the body or the head section of an HTML page or inside both the
head and body. We can also place JavaScript outside the HTML file which can be linked by specifying its
source in the script tag.
Add JavaScript Code inside Head Section
JavaScript code is placed inside the head section of an HTML page and the function is invoked when a
button is clicked.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Add JavaScript Code inside Head Section
</title>
<script>
function myFun() {
document.getElementById("demo")
.innerHTML = "Content changed!";
}
</script>
</head>
<body>
<h3 id="demo" style="color:green;">
Welcome to Javascript
</h3>
<button type="button" onclick="myFun()">
Click Here
</button>
7

</body>
</html>
Add JavaScript Code inside Body Section
JavaScript Code is placed inside the body section of an HTML page and the function is invoked when a
button is clicked.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript </title>
</head>
<body>
<h2>
Add JavaScript Code
inside Body Section
</h2>
<h3 id="demo" style="color:green;">
GeeksforGeeks
</h3>
<button type="button" onclick="myFun()">
Click Here
</button>
<script>
function myFun() {
document.getElementById("demo")
.innerHTML = "Content changed!";
}
</script>
</body>
</html>
External JavaScript
JavaScript can also be used in external files. The file extension of the JavaScript file will be .js. To use an
external script put the name of the script file in the src attribute of a script tag. External scripts cannot
contain script tags.
Example:
Script.js
External JavaScript
8

JavaScript can also be used in external files. The file extension of the JavaScript file will be .js. To use an
external script put the name of the script file in the src attribute of a script tag. External scripts cannot
contain script tags.
Example:
Script.js
function myFun () {
document.getElementById('demo')
.innerHTML = 'Paragraph Changed'
}
<!DOCTYPE html>
<html>
<head>
<title>
External JavaScript
</title>
</head>
<body>
<h3 id="demo" style="color:green;">
GeeksforGeeks
</h3>
<button type="button" onclick="myFun()">
Click Here
</button>
</body></html>
Advantages of External JavaScript
 Cached JavaScript files can speed up page loading.
 It makes JavaScript and HTML easier to read and maintain.
 It separates the HTML and JavaScript code.
 It focuses on code reusability which is one JavaScript Code that can run in various HTML files.

JavaScript Data Types


JavaScript provides different data types to hold different types of values. There are two types of data types
in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
9

JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is
dynamically used by JavaScript engine. You need to use var here to specify the data type. It can hold any
type of values such as numbers, strings etc. For example:
var a=40;//holding number
var b="Rahul";//holding string

JavaScript primitive data types


There are five types of primitive data types in JavaScript. They are as follows:
Data Type Description
String represents sequence of characters e.g. "hello"
Number represents numeric values e.g. 100
Boolean represents boolean value either false or true
Undefined represents undefined value
Null represents null i.e. no value at all

JavaScript non-primitive data types


The non-primitive data types are as follows:
Data Type Description
Object represents instance through which we can access members
Array represents group of similar values
RegExp represents regular expression

JavaScript Operators
JavaScript operators operate the operands, these are symbols that are used to manipulate a certain value or
operand. Operators are used to performing specific mathematical and logical computations on operands.
In other words, we can say that an operator operates the operands.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Arithmetic Operators
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No. Operator & Description
1 + (Addition)
10

Adds two operands


Ex: A + B will give 30
2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9

Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".

<html>
<body>
<script type = "text/javascript">
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";

document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);

document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);

document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);

document.write("a + b + c = ");
result = a + b + c;
document.write(result);
11

document.write(linebreak);

a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);

b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>

Set the variables to different values and then try...


</body>
</html>

Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Comparison Operators
Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

= = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
1
becomes true.
Ex: (A == B) is not true.

!= (Not Equal)
Checks if the value of two operands are equal or not, if the values are not
2
equal, then the condition becomes true.
Ex: (A != B) is true.

> (Greater than)


Checks if the value of the left operand is greater than the value of the right
3
operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
12

< (Less than)


Checks if the value of the left operand is less than the value of the right
4
operand, if yes, then the condition becomes true.
Ex: (A < B) is true.

>= (Greater than or Equal to)


Checks if the value of the left operand is greater than or equal to the value of
5
the right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.

<= (Less than or Equal to)


Checks if the value of the left operand is less than or equal to the value of the
6
right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.

Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
document.write(result);
document.write(linebreak);
document.write("(a < b) => ");
result = (a < b);
document.write(result);
document.write(linebreak);
document.write("(a > b) => ");
result = (a > b);
document.write(result);
document.write(linebreak);
document.write("(a != b) => ");
result = (a != b);
document.write(result);
document.write(linebreak);
document.write("(a >= b) => ");
13

result = (a >= b);


document.write(result);
document.write(linebreak);
document.write("(a <= b) => ");
result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and different operators and then try...
</body>
</html>

Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...

Logical Operators
Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

&& (Logical AND)


1 If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.

|| (Logical OR)
2 If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.

! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical
3
NOT operator will make it false.
Ex: ! (A && B) is false.
14

Example

Try the following code to learn how to implement Logical Operators in JavaScript.

<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";

document.write("(a && b) => ");


result = (a && b);
document.write(result);
document.write(linebreak);

document.write("(a || b) => ");


result = (a || b);
document.write(result);
document.write(linebreak);

document.write("!(a && b) => ");


result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...
15

Bitwise Operators
Assume variable A holds 2 and variable B holds 3, then −

Sr.No. Operator & Description

& (Bitwise AND)


1 It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.

| (BitWise OR)
2 It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.

^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer
3 arguments. Exclusive OR means that either operand one is true or operand two
is true, but not both.
Ex: (A ^ B) is 1.

~ (Bitwise Not)
4 It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.

<< (Left Shift)


It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a
5
value left by one position is equivalent to multiplying it by 2, shifting two
positions is equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.

>> (Right Shift)


Binary Right Shift Operator. The left operand’s value is moved right by the
6
number of bits specified by the right operand.
Ex: (A >> 1) is 1.

>>> (Right shift with Zero)


This operator is just like the >> operator, except that the bits shifted in on the
7
left are always zero.
Ex: (A >>> 1) is 1.

Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
16

var linebreak = "<br />";

document.write("(a & b) => ");


result = (a & b);
document.write(result);
document.write(linebreak);

document.write("(a | b) => ");


result = (a | b);
document.write(result);
document.write(linebreak);

document.write("(a ^ b) => ");


result = (a ^ b);
document.write(result);
document.write(linebreak);

document.write("(~b) => ");


result = (~b);
document.write(result);
document.write(linebreak);

document.write("(a << b) => ");


result = (a << b);
document.write(result);
document.write(linebreak);

document.write("(a >> b) => ");


result = (a >> b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
(a & b) => 2
17

(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then try...

Assignment Operators

Sr.No. Operator & Description

= (Simple Assignment )
1 Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C

+= (Add and Assignment)


It adds the right operand to the left operand and assigns the result to the left
2
operand.
Ex: C += A is equivalent to C = C + A

−= (Subtract and Assignment)


It subtracts the right operand from the left operand and assigns the result to the
3
left operand.
Ex: C -= A is equivalent to C = C - A

*= (Multiply and Assignment)


It multiplies the right operand with the left operand and assigns the result to
4
the left operand.
Ex: C *= A is equivalent to C = C * A

/= (Divide and Assignment)


It divides the left operand with the right operand and assigns the result to the
5
left operand.
Ex: C /= A is equivalent to C = C / A

%= (Modules and Assignment)


6 It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A

Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.

Example
<html>
<body>
<script type = "text/javascript">
<!--
18

var a = 33;
var b = 10;
var linebreak = "<br />";

document.write("Value of a => (a = b) => ");


result = (a = b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a += b) => ");


result = (a += b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a -= b) => ");


result = (a -= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a *= b) => ");


result = (a *= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a /= b) => ");


result = (a /= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a %= b) => ");


result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
</body>
</html>
19

Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0

Conditional Operator (? :)

The conditional operator first evaluates an expression for a true or false value and then executes one of the
two given statements depending upon the result of the evaluation.

Sr.No. Operator and Description

? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y

Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write ("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write ("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>
20

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...

typeof Operator

 The typeof operator is a unary operator that is placed before its single operand, which can be of any
type. Its value is a string indicating the data type of the operand.
 The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string,
or booleanvalue and returns true or false based on the evaluation.
 Here is a list of the return values for the typeof Operator.

Type String Returned by typeof

Number "number"

String "string"

Boolean "boolean"

Object "object"

Function "function"

Undefined "undefined"

Null "object"

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

var a = 10;
var b = "String";
var linebreak = "<br />";

result = (typeof b == "string" ? "B is String" : "B is Numeric");


21

document.write("Result => ");


document.write(result);
document.write(linebreak);

result = (typeof a == "string" ? "A is String" : "A is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
</body>
</html>

Output
Result => B is String
Result => A is Numeric

Conditional Statements in JavaScript


Conditional statements in JavaScript allow you to execute specific blocks of code based on conditions. If
the condition meets then a particular block of action will be executed otherwise it will execute another
block of action that satisfies that particular condition.
There are several methods that can be used to perform Conditional Statements in JavaScript.
 if Statement
 if-else Statement
 else if Statement
 switch Statement
 Ternary Operator
JavaScript if Statement
The if statement is used to evaluate a particular condition. If the condition holds true, the associated code
block is executed.
Syntax:
if ( condition ) {
statement(s)
}
Example: In this example, we are using the if statement to find given number is even or odd.
let num = 20;
if (num % 2 === 0)
22

{
console.log("Given number is even number.");
}
if (num % 2 !== 0)
{
console.log("Given number is odd number.");
}
JavaScript if-else Statement
The if-else statement will perform some action for a specific condition. Here we are using the else
statement in which the else statement is written after the if statement and it has no condition in their code
block.
if ( condition )
{
statement(s)
}
else
{
statements(s)
}
Example:
let age = 25;
if (age >= 18) {
document.write("You are eligible of driving licence")
} else {
document.write("You are not eligible for driving licence")
}

JavaScript else if Statement


The else if statement in JavaScript allows handling multiple possible conditions and outputs, evaluating
more than two options based on whether the conditions are true or false.
Syntax:
if (condition1) {
statements(s)
} else if (condition1) {
statements(s)
} else if (condition1) {
23

statements(s)
} else {
statements(s)
}
Example:
const num = 0;
if (num > 0) {
console.log("Given number is positive.");
} else if (num < 0) {
console.log("Given number is negative.");
} else {
console.log("Given number is zero.");
}
JavaScript Switch Statement
As the number of conditions increases, you can use multiple else-if statements in JavaScript. but when we
dealing with many conditions, the switch statement may be a more preferred option.
Syntax:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
default:
statementDefault;
}
const marks = 85;
let Branch;
switch (true) {
case marks >= 90:
Branch = "Computer science engineering";
break;
24

case marks >= 80:


Branch = "Mechanical engineering";
break;
case marks >= 70:
Branch = "Chemical engineering";
break;
case marks >= 60:
Branch = "Electronics and communication";
break;
case marks >= 50:
Branch = "Civil engineering";
break;
default:
Branch = "Bio technology";
break;
}
document.write(“Student Branch name is”+Branch);

JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It
makes the code compact. It is mostly used in array.
There are mainly two types of loops:
 Entry Controlled Loop: In these types of loops, the test condition is tested before entering the loop
body. The for Loop and while Loop are entry-controlled loops.
 Exit Controlled Loop: In these types of loops the test condition is tested or evaluated at the end of the
loop body. Therefore, the loop body will execute at least once, irrespective of whether the test
condition is true or false. The do-while loop is exit controlled loop.
1) JavaScript For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of
iteration is known.
Syntax
xfor (initialization; condition; increment/decrement)
{
code to be executed
}
25

Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already
declared variable can be used or a variable can be declared, local to loop only.
Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is
also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
Statement execution: Once the condition is evaluated to be true, the statements in the loop body are
executed.
Increment/ Decrement: It is used for updating the variable for the next iteration.
Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
JavaScript while loop
A while loop is a control flow statement that allows code to be executed repeatedly based on a given
Boolean condition.The syntax of while loop is given below.
while (condition)
{
code to be executed
}

 While loop starts with checking the condition. If it is


evaluated to be true, then the loop body statements are executed otherwise first statement following
the loop is executed. For this reason, it is also called the Entry control loop
 Once the condition is evaluated to be true, the statements in the loop body are executed. Normally the
statements contain an updated value for the variable being processed for the next iteration.
 When the condition becomes false, the loop terminates which marks the end of its life cycle.
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
JavaScript do while loop
26

The do-while loop is similar to the while loop with the only difference is that it checks for the condition
after executing the statements, and therefore is an example of an Exit Control Loop.But, code is executed
at least once whether condition is true or false.
The syntax of do while loop
do{
code to be executed
}while (condition);
 The do-while loop starts with the execution of the
statement(s). There is no checking of any condition for the first time.
 After the execution of the statements and update of the variable value, the condition is checked for a
true or false value. If it is evaluated to be true, the next iteration of the loop starts.
 When the condition becomes false, the loop terminates which marks the end of its life cycle.
 It is important to note that the do-while loop will execute its statements at least once before any
condition is checked and therefore is an example of the exit control loop.
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>

JavaScript for in loop


For-in loop in JavaScript is used to iterate over the properties of an object. The for-in loop iterates
only over those keys of an object which have their enumerable property set to “true”.

Syntax

for (x in object) {
code block to be executed
}
Parameters
Parameter Description
x Required.
A variable to iterate over the properties.
object Required.
The object to be iterated

example
27

const person = {fname:"John", lname:"Doe", age:25};


let text = "";
for (let x in person) {
text += person[x] + " ";
}
JavaScript break and continue
Break statement: The break statement is used to jump out of a loop. It can be used to “jump out” of a
switch() statement. It breaks the loop and continues executing the code after the loop.

for (let i = 0; i < 10; i++) {


if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
Continue statement: The continue statement “jumps over” one iteration in the loop. It breaks iteration in
the loop and continues executing the next iteration in the loop.
for (let i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}

JavaScript Popup Boxes


28

In JavaScript, popup boxes are used to display the message or notification to the user. JavaScript has three
kinds of popup boxes: 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
window.alert("sometext");
The window.alert() method can be written without the window prefix.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
Confirm Box
 A confirm box is often used if you want the user to verify or accept something.
 When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
 If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

Syntax:

window.confirm("sometext");

The window.confirm() method can be written without the window prefix.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
29

<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>

Prompt Box
 A prompt box is often used if you want the user to input a value before entering a page.
 When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after
entering an input value.
 If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax
window.prompt("SOME MESSAGE", "DEFAULT_VALUE");
Here, SOME MESSAGE is the message which is displayed in the popup box,
and DEFAULT_VALUE is the default value in the input field. The default value is an optional field.
The window.prompt() method can be written without the window prefix.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text;
let person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
text = "User cancelled the prompt.";
30

} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
Example
<html>
<body>
<script type="text/javascript">
var name=prompt("enter your name")
var result=confirm("do you want to save");
if(result)
{
alert("You have clicked ok button");
}
else
{
document.write("You have clicked cancel button");
}
</script>
</body>
</html>

Write() and Writeln()


Write() method displays the output but do not provide a new line character.
Syntax:
document.write( exp1, exp2, exp3, ... )

<script>
Hello World!Have a nice day!
document.write("Hello World!");

document.write("Have a nice day!");

</script>
31

WriteLine() method displays the output and also provides a new line character it the end of the string, This
would set a new line for the next output.
Syntax:
document.writeln( exp1, exp2, exp3, ... )

<script>
Hello World!
document.writeln("Hello World!"); Have a nice day!

document.writeln("Have a nice day!");

</script>

JavaScript Output

There are certain situations in which you may need to generate output from your JavaScript code. For
example, you might want to see the value of variable, or write a message to browser console to help you
debug an issue in your running JavaScript code, and so on.
In JavaScript there are several different ways of generating output including
Writing into an HTML element, using innerHTML.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
Writing Output to Browser Console
You can easily outputs a message or writes data to the browser console
using the console.log() method.
For debugging purposes, you can call the console.log() method in the browser to
displaydata.
Eg
<!DOCTYPE html>
<html>
<head>
<title>Writing into the Browser's Console with JavaScript</title>
</head>
<body>
<script>
// Printing a simple text message
console.log("Hello World!"); // Prints: Hello World!
// Printing a variable
value var x = 10;
32

var y = 20;
var sum = x + y;
console.log(sum); // Prints: 30
</script>
<p><strong>Note:</strong> Please check out the browser console by pressing the
f12 key on the keyboard.</p>
</body>
</html>
Displaying Output in Alert Dialog Boxes
You can also use alert dialog boxes to display the message or output data to the user. An alert dialog
box is created using the window.alert() method.
example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Writing into an Alert Dialog Box with JavaScript</title>
</head>
<body>
<script>
// Displaying a simple text message alert("Hello World!"); // Outputs: Hello World!
// Displaying a variable
value var x = 10;
var y = 20;
var sum = x + y;
alert(sum); //
Outputs: 30
</script>
</body>
</html>
Example 2
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script> window.alert(5 + 6);
</script>
33

</body>
</html>

 You can skip the window keyword.


 In JavaScript, the window object is the global scope object, that means that variables, properties,
and methods by default belongs to the window object. This also means that specifying the window
keyword is optional:
Writing Output to the Browser Window
You can use the document.write() method to write the content to the current document only
while that document is being parsed.
example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Writing into an Browser Window with JavaScript</title>
</head>
<body>
<script>
// Printing a simple text message document.write("Hello World!"); // Prints: Hello World!
// Printing a variable
value var x = 10;
var y = 20;
var sum = x + y;
document.write(sum); //
Prints: 30
</script>
</body>
</html>
If you use the document.write() method method after the page has been loaded, it will
overwrite all the existing content in that document. Check out the following example:
<!DOCTYPE html>
<html>
<head>
<title>Problem with JavaScript Document.write() Method</title>
</head>
<body>
34

<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
<button type="button" onclick="document.write('Hello World!')">Click Me</button>
</body>
</html>
Inserting Output Inside an HTML Element
You can also write or insert output inside an HTML element using the element's innerHTML
property. However, before writing the output first we need to select the element using a
method such as getElementById()
The id attribute defines the HTML element. The innerHTML property defines the HTML
content.
Changing the innerHTML property of an HTML element is a common way to display data in
HTML.,
Example:
<!DOCTYPE html>
<html>
<head>
<title>Writing into an HTML Element with JavaScript</title>
</head>
<body>
<p id="greet"></p>
<p id="result"></p>
<script>
// Writing text string inside an element
document.getElementById("greet").innerHTML = "Hello World!";
// Writing a variable value inside an element var x = 10;
var y = 20;
var sum = x + y; document.getElementById("result").innerHTML = sum;
</script>
</body>
</html>

Example2
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
35

<p>My First Paragraph.</p>


<p id="demo"></p>
<script> document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
JavaScript Print

JavaScript does not have any print object or print methods.


You cannot access output devices from JavaScript.
The only exception is that you can call the
window.print() method in the browser to print the content of the current window.

<!DOCTYPE html>

<html>

<body>

<h2>The window.print() Method</h2>

<p>Click the button to print the current page.</p>

<button onclick="window.print()">Print this page</button>

</body>
</html>

JavaScript Global Methods and Properties

isNaN()
 In JavaScript NaN is short for "Not-a-Number".
 The isNaN() method returns true if a value is NaN.
 The isNaN() method converts the value to a number before testing it.
Syntax
isNaN(value)
Parameters
Parameter Description
value Required.
The value to be tested.
36

Return Value
Type Description
A boolean true if the value is NaN, otherwise false.
<p id="demo"></p>
<script>
Is 123 NaN? false
let result = Is -1.23 NaN? false
Is 5-2 NaN? false
"Is 123 NaN? " + isNaN(123) + "<br>" +
Is 0 NaN? false
"Is -1.23 NaN? " + isNaN(-1.23) + "<br>" +
Is 'Hello' NaN? true
"Is 5-2 NaN? " + isNaN(5-2) + "<br>" + Is '2005/12/12' NaN? true

"Is 0 NaN? " + isNaN(0)+ +

"Is '2005/12/12' NaN? " + isNaN('2005/12/12');;

document.getElementById("demo").innerHTML = result;
</script>
Number()
 The Number() method converts a value to a number.
 If the value cannot be converted, NaN is returned.
 For booleans, Number() returns 0 or 1.
 For dates, Number() returns milliseconds since January 1, 1970 00:00:00.
 For strings, Number() returns a number or NaN.
Syntax
Number(value)
Parameters
Parameter Description
value Optional.
A JavaScript value (variable).
Return Value
Type Description
A number Returns the value as a number.
If the value cannot be converted to a number, NaN is returned.
If no value is provided, 0 is returned.
<p id="demo"></p>
Number() converts a value to a
number if possible:

1
0
37

<script>
document.getElementById("demo").innerHTML =
Number(true) + "<br>" +
Number(false) + "<br>" +
Number(new Date());
</script>

parseInt()
 The parseInt method parses a value as a string and returns the first integer.
 A radix parameter specifies the number system to use:
 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal.
 If radix is omitted, JavaScript assumes radix 10. If the value begins with "0x", JavaScript assumes
radix 16.
Syntax
parseInt(string, radix)
Parameters
Parameter Description
value Required.
The value to be parsed.
radix Optional. Default is 10.
A number (2 to 36) specifying the number system.
Return Value
Type Description
A number. NaN if no integer is found.
<p id="demo"></p>
<script>
parseInt() parses a string and
document.getElementById("demo").innerHTML = returns the first integer:
parseInt("10") + "<br>" +
10
parseInt("10.00") + "<br>" +
10
parseInt("10.33") + "<br>" + 10
parseInt("34 45 66") + "<br>" + 34
60
parseInt(" 60 ") + "<br>" +
40
parseInt("40 years") + "<br>" + NaN
38

parseInt("He was 40");


</script>

parseFloat()
The parseFloat() method parses a value as a string and returns the first number.
Syntax
parseFloat(value)
Parameters
Parameter Description
value Required.
The value to parse.
Return Value
Type Description
A number NaN if no number is found.
<p id="demo"></p> 10
<script> 10
document.getElementById("demo").innerHTML = 10.33
34
parseFloat(10) + "<br>" + NaN
parseFloat("10") + "<br>" +
parseFloat("10.33") + "<br>" +
parseFloat("34 45 66") + "<br>" +
parseFloat("He was 40");
</script>

String()
The String() method converts a value to a string.
Syntax
String(value)
Parameters
Parameter Description
value Required.
A JavaScript value.
Return Value
39

Type Description
A string. The value converted to a string.
<p id="demo"></p>
<script> Tue Oct 31 2023 23:47:25 GMT+0530
document.getElementById("demo").innerHTML =
(India Standard Time)
12345
String(new Date()) + "<br>" +
12345
String("12345") + "<br>" +
String(12345);
</script>
JavaScript Functions
 A JavaScript function is a block of code designed to perform a particular task.
 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).
 The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
 The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
 Function parameters are listed inside the parentheses () in the function definition.
 Function arguments are the values received by the function when it is invoked.
 Inside the function, the arguments (the parameters) behave as local variables
Function Invocation
 The code inside the function will execute when "something" invokes (calls) the function:
 When an event occurs (when a user clicks a button)
 When it is invoked (called) from JavaScript code Automatically (self invoked)
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":
40

<p id="demo"></p>
<script>
function myFunction(p1, p2) { 12
return p1 * p2;
}
let result = myFunction(4, 3);
document.getElementById("demo").innerHTML = result;
</script>
<p id="demo"></p>
<script>
let x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
JavaScript Timing Events
The window object allows execution of code at specified time intervals.
These time intervals are called timing events.
The two key methods to use with JavaScript are:
 setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.
 setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.
The setTimeout() Method
window.setTimeout(function, milliseconds);
The window.setTimeout() method can be written without the window prefix.
The first parameter is a function to be executed.
The second parameter indicates the number of milliseconds before execution.
Example
<body>
<h2>JavaScript Timing</h2>
<p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>
41

<button onclick="setTimeout(myFunction, 3000);">Try it</button>


<script>
function myFunction() {
alert('Hello');
}
</script>
</body>
</html>
The clearTimeout() method stops the execution of the function specified in setTimeout().
window.clearTimeout(timeoutVariable)
The window.clearTimeout() method can be written without the window prefix.
The clearTimeout() method uses the variable returned from setTimeout():
myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);

The setInterval() Method


The setInterval() method repeats a given function at every given time-interval.
window.setInterval(function, milliseconds);
The window.setInterval() method can be written without the window prefix.
The first parameter is the function to be executed.
The second parameter indicates the length of the time-interval between each execution.
This example executes a function called "myTimer" once every second (like a digital watch).
<p id="demo"></p>
<script>
setInterval(myTimer, 1000);
function myTimer() {
const d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>

JavaScript Events
he change in the state of an object is known as an Event. In html, there are various events which represents
that some activity is performed by the user or by the browser. When javascript code is included in HTML, js
42

react over these events and allow the execution. This process of reacting over the events is called Event
Handling. Thus, js handles the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to be performed
on the event.

 An HTML web page has finished loading


 An HTML input field was changed
 An HTML button was clicked
Syntax:
<HTML-element Event-Type = "Action to be performed">

Some of the HTML events and their event handlers are:


Mouse events:

Event Performed Event Handler Description


click onclick When mouse click on an element
mouseover onmouseover When the cursor of the mouse comes over the element
mouseout onmouseout When the cursor of the mouse leaves an element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
mousemove onmousemove When the mouse movement takes place.
Keyboard events:

Event Performed Event Handler Description


Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:

Event Performed Event Handler Description


focus onfocus When the user focuses on an element
submit onsubmit When the user submits the form
blur onblur When the focus is away from a form element
change onchange When the user modifies or changes the value of a form element
43

Window/Document events

Event Performed Event Handler Description


load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the browser unloads it
resize onresize When the visitor resizes the window of the browser

Click Event
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is JavaTpoint");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>

MouseOver Event
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
44

//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
Focus Event
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
//-->
</script>
</body>
Keydown Event
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
Load event
<body onload="window.alert('Page successfully loaded');">
<script>
45

<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>

JavaScript onblur event:


<body style="margin-left: 40%;">
<p>Write something in the input box and then click elsewhere
in the document body.</p>
<input onblur="alert(this.value)">
</body>

onChange() event

<body>

<input onchange="alert(this.value)"

type="number"

style="margin-left: 45%;">

</body>

onSubmit() event

<form action="/action_page.php" onsubmit="myFunction()">

Enter name: <input type="text" name="fname">

<input type="submit" value="Submit">

</form>

<script>

function myFunction() {

alert("The form was submitted");

</script>
46

JavaScript HTML DOM


The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows
programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents

With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM is a standard object model and programming interface for HTML. It defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements

The HTML DOM model is constructed as a tree of Objects:

With the object model, JavaScript gets all the power it needs to create dynamic HTML:
 JavaScript can change all the HTML elements in the page
 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
47

 JavaScript can add new HTML elements and attributes


 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

JavaScript Date Objects


Date objects are created with the new Date() constructor.
There are 9 ways to create a new date object:
new Date()
new Date(date string)
new Date(year,month)
new Date(year,month,day)
new Date(year,month,day,hours)
new Date(year,month,day,hours,minutes)
new Date(year,month,day,hours,minutes,seconds)
new Date(year,month,day,hours,minutes,seconds,ms)
new Date(milliseconds)
JavaScript new Date()
new Date() creates a date object with the current date and time:
Example
const d = new Date();
new Date(date string)
new Date(date string) creates a date object from a date string:
Examples
const d = new Date("October 13, 2014 11:13:00");
const d = new Date("2022-03-25");
new Date(year, month, ...)
new Date(year, month, ...) creates a date object with a specified date and time.
7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):
Example
const d = new Date(2018, 11, 24, 10, 33, 30, 0);

<body>
<h1>JavaScript Dates</h1>
<h2>Using new Date()</h2>
48

<p id="demo"></p>
<script>
const d = new Date("2022-03-25");
document.getElementById("demo").innerHTML = d;
</script>
</body>
JavaScript Date Methods
Methods Description
getDate() It returns the integer value between 1 and 31 that represents the day for the specified
date on the basis of local time.
getDay() It returns the integer value between 0 and 6 that represents the day of the week on the
basis of local time.
getFullYears() It returns the integer value that represents the year on the basis of local time.
getHours() It returns the integer value between 0 and 23 that represents the hours on the basis of
local time.
getMilliseconds() It returns the integer value between 0 and 999 that represents the milliseconds on the
basis of local time.
getMinutes() It returns the integer value between 0 and 59 that represents the minutes on the basis of
local time.
getMonth() It returns the integer value between 0 and 11 that represents the month on the basis of
local time.
getSeconds() It returns the integer value between 0 and 60 that represents the seconds on the basis of
local time.
getUTCDate() It returns the integer value between 1 and 31 that represents the day for the specified
date on the basis of universal time.
getUTCDay() It returns the integer value between 0 and 6 that represents the day of the week on the
basis of universal time.
getUTCFullYears() It returns the integer value that represents the year on the basis of universal time.
getUTCHours() It returns the integer value between 0 and 23 that represents the hours on the basis of
universal time.
getUTCMinutes() It returns the integer value between 0 and 59 that represents the minutes on the basis of
universal time.
getUTCMonth() It returns the integer value between 0 and 11 that represents the month on the basis of
49

universal time.
getUTCSeconds() It returns the integer value between 0 and 60 that represents the seconds on the basis of
universal time.
setDate() It sets the day value for the specified date on the basis of local time.
setDay() It sets the particular day of the week on the basis of local time.
setFullYears() It sets the year value for the specified date on the basis of local time.
setHours() It sets the hour value for the specified date on the basis of local time.
setMilliseconds() It sets the millisecond value for the specified date on the basis of local time.
setMinutes() It sets the minute value for the specified date on the basis of local time.
setMonth() It sets the month value for the specified date on the basis of local time.
setSeconds() It sets the second value for the specified date on the basis of local time.
toDateString() It returns the date portion of a Date object.
toString() It returns the date in the form of string.
valueOf() It returns the primitive value of a Date object.
JavaScript Current Time Example
Current Time: <span id="txt"></span>
<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>

JavaScript Array
An Array is a collection of data and a data structure that is stored in a sequence of memory locations.
One can access the elements of an array by calling the index number such as 0, 1, 2, 3, …, etc. The array
can store data types like Integer, Float, String, and Boolean all the primitive data types can be stored
in an array.There are 3 ways to construct array in JavaScript

1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
50

1) JavaScript array literal


The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't have to
provide value explicitly.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
51

Array Properties
The following table lists the standard properties of the Array object.
Property Description
length Sets or returns the number of elements in an array.
prototype Allows you to add new properties and methods to an Array object.

Array Methods
Method Description
concat() Merge two or more arrays, and returns a new array.
fill() Fill the elements in an array with a static value.
filter() Creates a new array with all elements that pass the test in a testing function.
find() Returns the value of the first element in an array that pass the test in a testing function.
findIndex() Returns the index of the first element in an array that pass the test in a testing function.
forEach() Calls a function once for each array element.
from() Creates an array from an object.
includes() Determines whether an array includes a certain element.
indexOf() Search the array for an element and returns its first index.
isArray() Determines whether the passed value is an array.
join() Joins all elements of an array into a string.
keys() Returns a Array Iteration Object, containing the keys of the original array.
lastIndexOf() Search the array for an element, starting at the end, and returns its last index.
map() Creates a new array with the results of calling a function for each array element.
pop() Removes the last element from an array, and returns that element.
push() Adds one or more elements to the end of an array, and returns the array's new length.
reverse() Reverses the order of the elements in an array.
shift() Removes the first element from an array, and returns that element.
slice() Selects a part of an array, and returns the new array.
some() Checks if any of the elements in an array passes the test in a testing function.
sort() Sorts the elements of an array.
splice() Adds/Removes elements from an array.
toString() Converts an array to a string, and returns the result.
unshift() Adds new elements to the beginning of an array, and returns the array's new length.
values() Returns a Array Iteration Object, containing the values of the original array.
52

Array length

The length property returns the length (size) of an array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;

join()

The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");

Array pop()

The pop() method removes the last element from an array:

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.pop();

Array push()

The push() method adds a new element to an array (at the end):

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.push("Kiwi");

Merging (Concatenating) Arrays

The concat() method creates a new array by merging (concatenating) existing arrays:

Example (Merging Two Arrays)


const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);
53

JavaScript String

 JavaScript String Object is a sequence of characters. It contains zero or more characters within
single or double quotes.
 In JavaScript, strings automatically convert the string to objects so that we can use string methods
and properties also for primitive strings

Syntax:
const string_name = "String Content"
or
const string_name = new String("String Content")

Example: In this example, we will create a string by using the native way and using String Constructor.
// Create a variable and assign String value
const str1 = "First String Content";
console.log("String 1: " + str1);
// Creating a String using String() Constructor
const str2 = String("Second String Content");
console.log("String 2: " + str2);

JavaScript String Length


The length property returns the length of a string:
Example
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;

You might also like