Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Java Script

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Java Script

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

1

JavaScript - Overview
JS stands for JavaScript. It is a text-based, lightweight, cross-platform, and
interpreted scripting programming language. This language is very popular for
developing web pages. It can be used both on the client-side and server-side.

In September 1995, a Netscape programmer named Brandan Eich developed a


new scripting language in just 10 days. It was originally named Mocha, but
quickly became known as LiveScript and, later, JavaScript.

LiveScript, JScript, ECMAScript, ES are all just alternative names for


JavaScript.

Why is JavaScript used?

JavaScript is a scripting language used to develop web pages. Developed in


Netscape, JS allows developers to create a dynamic and interactive web page to
interact with visitors and execute complex actions. It also enables users to load
content into a document without reloading the entire page.

What is JS in HTML?

JavaScript is the Programming Language for the Web. JavaScript can update
and change both HTML and CSS.

Summary:

● JavaScript is a lightweight, interpreted programming language.


● Designed for creating network-centric applications.
● Complementary to and integrated with Java.
● Complementary to and integrated with HTML.
● Open and cross-platform
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
2

Advantages of JavaScript
The merits of using JavaScript are −

● Less server interaction − You can validate user input before sending the
page off to the server. This saves server traffic, which means less load on
your server.
● Immediate feedback to the visitors − They don't have to wait for a page
reload to see if they have forgotten to enter something.
● Increased interactivity − You can create interfaces that react when the
user hovers over them with a mouse or activates them via the keyboard.
● Richer interfaces − You can use JavaScript to include such items as
drag-and-drop components and sliders to give a Rich Interface to your site
visitors.

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features −

● Client-side JavaScript does not allow the reading or writing of files. This
has been kept for security reason.
● JavaScript cannot be used for networking applications because there is no
such support available.
● JavaScript doesn't have any multi-threading or multiprocessor capabilities.

Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:

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

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
3

What is JavaScript ?
JavaScript is a dynamic computer programming language. It is lightweight and
most commonly used as a part of web pages, whose implementations allow
client-side script to interact with the user and make dynamic pages. It is an
interpreted programming language with object-oriented capabilities.

JavaScript enables developers to create dynamic and interactive web pages by


manipulating the content and behavior of web elements in response to user
actions or events.

Here are some key aspects of JavaScript:

1. Client-Side Scripting: JavaScript is mainly used as a client-side scripting


language, meaning it runs in the user's web browser rather than on the
web server. This allows for dynamic updates to content, user interface
interactions, form validations, and more without requiring a page reload.
2. Syntax and Grammar: JavaScript syntax is similar to other programming
languages like Java and C, making it relatively easy to learn for developers
familiar with those languages. It uses variables, data types, operators,
control structures (such as loops and conditional statements), functions,
and objects.
3. Event-Driven Programming: JavaScript is event-driven, meaning it
responds to events triggered by user interactions or changes in the
browser environment. Examples of events include mouse clicks, keyboard
inputs, page loading, form submissions, and timer expirations. Developers
can attach event handlers to HTML elements to execute JavaScript code in
response to these events.
4. DOM Manipulation: The Document Object Model (DOM) is a
programming interface provided by web browsers that represents the
structure of HTML documents as a tree-like structure of objects. JavaScript
can manipulate the DOM to dynamically update the content, structure, and
style of web pages. This allows for tasks like adding or removing HTML
elements, modifying their attributes or styles, and responding to user
interactions.
5. Asynchronous Programming: JavaScript supports asynchronous
programming, allowing tasks to be executed independently of the main
program flow. This is commonly used for tasks such as fetching data from

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
4

servers (AJAX("Asynchronous JavaScript and XML" )), handling user


input, or performing animations without blocking the execution of other
code.
6. Browser Compatibility: JavaScript is supported by all modern web
browsers, including Chrome, Firefox, Safari, Edge, and others. However,
developers need to be mindful of differences in JavaScript implementation
and browser quirks when writing cross-browser compatible code.
7. Frameworks and Libraries: JavaScript has a rich ecosystem of
frameworks and libraries that extend its capabilities and simplify common
tasks. Examples include React.js, AngularJS, Vue.js for building user
interfaces, jQuery for DOM manipulation, Node.js for server-side
JavaScript, and many others.

Overall, JavaScript is a versatile and powerful programming language that plays


a crucial role in modern web development, enabling developers to create
dynamic, interactive, and engaging web applications.

JavaScript - Syntax
● JavaScript can be implemented using JavaScript statements that are
placed within the <script>... </script> HTML tags in a web page.
● You can place the <script> tags, containing your JavaScript, anywhere
within your web page, but it is normally recommended that you should
keep it within the <head> tags.
● The <script> tag alerts the browser program to start interpreting all the text
between these tags as a script. A simple syntax of your JavaScript will
appear as follows.

<script ...>
JavaScript code
</script>

The script tag takes two important attributes −

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
5

● Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML
(and XHTML, its successor) have phased out the use of this attribute.
● Type − This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".

Example:−

<html>
<body>
<h2>Welcome to JavaScript</h2>
<script language = "javascript" type = "text/javascript">
document.write("Hello JavaScript by JavaScript");
</script>
</body>
</html>

3 Places to put JavaScript code


1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)

1) JavaScript Example : code between the body tag


In the above example, we have displayed the dynamic content using JavaScript. Let’s
see the simple example of JavaScript that displays alert dialog box.

Example:

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

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
6

alert("Hello SRM Students!");


</script>
</body>
</html>

Output:

2) JavaScript Example : code between the head tag


Let’s see the same example of displaying alert dialog box of JavaScript that is
contained inside the head tag.

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
7

In this example, we are creating a function msg(). To create function in JavaScript, you
need to write function with function_name as given below.

To call function, you need to work on event. Here we are using onclick event to call
msg() function.

<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
8

3) External JavaScript file


We can create external JavaScript files and embed it in many html pages.

It provides code re-usability because a 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.

Let's create an external JavaScript file that prints Hello Javatpoint in an alert dialog box.

message.js

function msg(){

alert("Hello Javatpoint");

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
9

Let's include the JavaScript file into the html page. It calls the JavaScript function on
button click.

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()"/>

</form>

</body>

</html>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
10

JavaScript Introduction
JavaScript Comments

The JavaScript comments are a meaningful way to deliver messages. It is used to add
information about the code, warnings or suggestions so that end users can easily
interpret the code.

The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the
browser.

Advantages of JavaScript comments

There are mainly two advantages of JavaScript comments.

1. To make code easy to understand It can be used to elaborate the code so that
end users can easily understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being
executed. Sometimes, we add the code to perform some action. But after
sometime, there may be a need to disable the code. In such case, it is better to
use comments.

Types of JavaScript Comments


There are two types of comments in JavaScript.

1. Single-line Comment (//)

2. Multi-line Comment (/*.....*/)

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
11

JavaScript variable
A JavaScript variable is simply the name of a storage location.

There are two types of variables in JavaScript : local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.


2. After the first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different
variables.

Example:

1. var x = 10;
2. var _value="sonoo";

What is the purpose of the let, const, and var keywords in JavaScript, and
how do they differ?

The `let`, `const`, and `var` keywords are used for variable declaration in
JavaScript, but they have some differences in terms of scope, reassignment, and
hoisting:

1. var:
→ Variables declared with `var` are function-scoped, meaning they are
accessible within the function in which they are declared.
→ `var` variables can be reassigned and re-declared within the same scope
without generating an error.
→ `var` variables are hoisted to the top of their function scope, meaning they
are available throughout the entire function regardless of where they are
declared.

Example:
function example() {

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
12

var x = 10;
if (true) {
var x = 20; // This reassigns the outer 'x'
console.log(x); // Outputs: 20
}
console.log(x); // Outputs: 20
}

2. `let`:
→ Variables declared with `let` are block-scoped, meaning they are only
accessible within the block (e.g., within loops, conditionals, or function bodies) in
which they are declared.
→ `let` variables can be reassigned, but attempting to redeclare them in the
same scope will result in an error.
→ `let` variables are not hoisted to the top of their block scope, so they are not
accessible before the declaration statement.

Example:
function example() {
let x = 10;
if (true) {
let x = 20; // This creates a new 'x' within the block
console.log(x); // Outputs: 20
}
console.log(x); // Outputs: 10
}

3.`const`:
→ Variables declared with `const` are also block-scoped.
→ `const` variables must be assigned a value when they are declared, and
once assigned, their value cannot be changed (i.e., they are immutable).
→ Attempting to reassign a `const` variable will result in an error, but the value
of a `const` variable that holds an object or array can still be modified.

Example:

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
13

function example() {
const x = 10;
x = 20; // This will cause an error
}

`var` is function-scoped and allows redeclaration and reassignment, `let` is


block-scoped and allows reassignment but not redeclaration in the same scope,
and `const` is also block-scoped but does not allow reassignment after
declaration (though it allows modification of the value if it's an object or array).

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

JavaScript is a dynamic type language, that is we don't need to specify the type of the
variable because it is dynamically used by the 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:

1. var a=40;//holding number


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

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
14

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 are symbols that are used to perform operations on operands.

There are following types of operators in JavaScript.

1. Arithmetic Operators

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
15

2. Comparison (Relational) Operators


3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison/Relational Operators


The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
16

Operator Description Example

== Is equal to 10==20 => false

=== Identical (equal and of same type) 10==20 => false

!= Not equal to 10!=20 => true

!== Not Identical 20!==20 => false

> Greater than 20>10 => true

>= Greater than or equal to 20>=10 => true

< Less than 20<10 => false

<= Less than or equal to 20<=10 => false

JavaScript Bitwise Operators


The bitwise operators perform bitwise operations on operands. The bitwise operators
are as follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) => false

| Bitwise OR (10==20 | 20==33) => false

^ Bitwise XOR (10==20 ^ 20==33) => false

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
17

~ Bitwise NOT (~10) => -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) => false

|| Logical OR (10==20 || 20==33) => false

! Logical Not !(10==20) = true

JavaScript Assignment Operators


The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
18

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators


The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is

like if-else.

, Comma Operator allows multiple expressions to be evaluated as

single statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
19

JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript
action to be performed.

Here is a list of some of the keywords:

Keyword Description

var Declares a variable

let Declares a block variable

const Declares a block constant

if Marks a block of statements to be executed on a condition

switch Marks a block of statements to be executed in different cases

for Marks a block of statements to be executed in a loop

function Declares a function

return Exits a function

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
20

try Implements error handling to a block of statements

Control statements

JavaScript If-else Statements


The JavaScript if-else statement is used to execute the code whether condition is true or
false. There are three forms of if statement in JavaScript.

1. If Statement
2. If else statement
3. if else if statement

JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.

Syntax:

if(expression){

//content to be evaluated

Example:
<html>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
21

<body>
<script>
var a=20;
if(a>10)
{
document.write("value of a is greater than 10");
}
</script>
</body>
</html>

JavaScript If...else Statement


It evaluates the content whether condition is true of false. The syntax of JavaScript
if-else statement is given below.

Syntax:

if(expression){

//content to be evaluated if condition is true

else{

//content to be evaluated if condition is false

Example:
<html>
<body>
<script>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
22

var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
</body>
</html>

JavaScript If...else if statement


It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.

Syntax:

if(expression1){

//content to be evaluated if expression1 is true

else if(expression2){

//content to be evaluated if expression2 is true

else if(expression3){

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
23

//content to be evaluated if expression3 is true

else{

//content to be evaluated if no expression is true

Example:

<html>
<body>
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
24

</body>
</html>

JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions.

But it is convenient than if..else..if because it can be used with numbers, characters etc.

Syntax:

switch(expression){

case value1:

code to be executed;

break;

case value2:

code to be executed;

break;

......

default:

code to be executed if above values are not matched;

Example:

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
25

<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
</body>
</html>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
26

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 four types of loops in JavaScript.

1. for loop

2. while loop

3. do-while loop

4. for-in 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. The syntax of for loop is given below.

for (initialization; condition; increment)


{
code to be executed
}

Example:

<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
27

}
</script>
</body>
</html>

2) JavaScript while loop


The JavaScript while loop iterates the elements for the infinite number of times. It should
be used if number of iteration is not known. The syntax of while loop is given below.

while (condition)

code to be executed

Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
28

</body>
</html>

3) JavaScript do while loop


The JavaScript do while loop iterates the elements for the infinite number of times like
while loop. But, code is executed at least once whether condition is true or false. The
syntax of do while loop is given below.

do{

code to be executed

}while (condition);

Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
29

4) JavaScript for in loop


The JavaScript for in loop is used to iterate the properties of an object.

Syntax
for (key in object) {

// code block to be executed

Example:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For In Loop</h2>


<p>The for in statement loops through the properties of an object:</p>

<p id="demo"></p>

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

var txt = " ";


for (var x in person) {
txt += person[x] + " ";
}

document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
30

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

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it saves coding.


2. Less coding: It makes our program compact. We don’t need to write many lines
of code each time to perform a common task.

Function Definition Syntax


A JavaScript function is defined with the function keyword, followed by a
name, followed by parentheses ().

Syntax:

function functionName([arg1, arg2, ...argN])


{
//code to be executed
}

JavaScript Functions can have 0 or more arguments.

Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:

1. When an event occurs (when a user clicks a button)


2. When it is invoked (called) from JavaScript code
3. Automatically (self invoked)

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
31

1.Example
<html>
<body>
<script>
function msg(){
alert("Function called when an event occur");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>

2.Example
<!DOCTYPE html>
<html>
<body>

Function Called <hr>

<script>

function myFunction() //function definition


{
document.write("Hi");
}

myFunction(); //function call

</script>

</body>
</html>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
32

3. Example:
<html>
<body>
<script>
//self invoking function
(function(){
alert("Auto Invoked Function");
})();
</script>
</body>
</html>

JavaScript Function Arguments


We can call functions by passing arguments.

Example:

<script>

function getcube(number)
{
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
33

Function with Return Value


We can call a function that returns a value and use it in our program.

Example:

<!Doctype html>

<html>

<body>

<script>

function add()
{
Var x=10,y=20;
return x+y;
}
var sum=add();
</script>

<script>
document.write(“addition=” + sum);

</script>

</body>
</html>

JavaScript Function Object


In JavaScript, the purpose of Function constructor is to create a new Function object. It
executes the code globally. However, if we call the constructor directly, a function is
created dynamically but in an unsecured way.

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
34

Syntax
new Function ([arg1[, arg2[, ....argn]],] functionBody)

arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.

Example:
<script>

var add=new Function("num1","num2","return num1+num2");

document.writeln(add(2,5));

</script>

JavaScript Function Methods


Let's see function methods with description.

Method Description

apply() It is used to call a function containing this value and a single array of

arguments.

bind() It is used to create a new function.

call() It is used to call a function containing this value and an argument list.

toString() It returns the result in the form of a string.

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
35

JavaScript Array
JavaScript array is an object that represents a collection of similar types of elements.

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)

1) JavaScript array literal


The syntax of creating array using array literal is given below:

var arrayname=[value1,value2.....valueN];

Example:
<html>
<body>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
36

var array_name = new Array();

Here, a new keyword is used to create an instance of an array.

Example:
<html>
<body>
<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>
</body>
</html>

3) JavaScript array constructor (new keyword)


Here, you need to create an instance of an array by passing arguments in the
constructor so that we don't have to provide value explicitly.

Example:
<html>
<body>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
37

<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>

JavaScript Array Methods


Let's see the list of JavaScript array methods with their description.

Methods Description

concat() It returns a new array object that contains two or more merged

arrays.

Syntax:

array.concat(arr1,arr2,....,arrn)
Example:

<script>

var arr1=["C","C++","Python"];

var arr2=["Java","JavaScript","Android"];

var result=arr1.concat(arr2);

document.writeln(result);

</script>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
38

copywithin() It copies the part of the given array with its own elements and

returns the modified array.

Syntax:

array.copyWithin(target, start, end)


Example:

<script>

var
arr=["AngularJS","Node.js","JQuery","Bootstrap"]

// place at 0th position, the element between 1st and 2nd position.

var result=arr.copyWithin(0,1,2);

document.writeln(result);

</script>

entries() It creates an iterator object and a loop that iterates over each

key/value pair.

every() It determines whether all the elements of an array are satisfying the

provided function conditions.

flat() It creates a new array carrying sub-array elements concatenated

recursively till the specified depth.

flatMap() It maps all array elements via mapping function, then flattens the

result into a new array.

fill() It fills elements into an array with static values.

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
39

from() It creates a new array carrying the exact copy of another array

element.

filter() It returns the new array containing the elements that pass the

provided function conditions.

find() It returns the value of the first element in the given array that

satisfies the specified condition.

findIndex() It returns the index value of the first element in the given array that

satisfies the specified condition.

forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the

index of the first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array,

then loops through these keys.

lastIndexOf() It searches the specified element in the given array and returns the

index of the last match.

map() It calls the specified function for every array element and returns the

new array

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
40

of() It creates a new array from a variable number of arguments, holding

any type of argument.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(functio It executes a provided function for each value from left to right and

n, initial) reduces the array to a single value.

reduceRight() It executes a provided function for each value from right to left and

reduces the array to a single value.

some() It determines if any element of the array passes the test of the

implemented function.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given

array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

toLocaleString It returns a string containing all the elements of a specified array.

()

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
41

toString() It converts the elements of a specified array into string form, without

affecting the original array.

unshift() It adds one or more elements in the beginning of the given array.

values() It creates a new iterator object carrying values for each index in the

array.

JavaScript String
The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

1. By string literal
2. By string object (using new keyword)

1) By string literal

The string literal is created using double quotes.

The syntax of creating string using string literal is given below:

var stringname="string value";

Example:

<!DOCTYPE html>
<html>
<body>
<script>
var str="This is string literal";

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
42

document.write(str);
</script>
</body>
</html>

2) By string object (using new keyword)

The syntax of creating string object using new keyword is given below:

var stringname=new String("string literal");

Here, new keyword is used to create instance of string.

Example:
<!DOCTYPE html>
<html>
<body>
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
</body>
</html>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
43

JavaScript String Methods

Methods Description

charAt() It provides the char value present at the specified index.

charCodeAt() It provides the Unicode value of a character present at the

specified index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given

string.

lastIndexOf() It provides the position of a char value present in the given

string by searching a character from the last position.

search() It searches a specified regular expression in a given string

and returns its position if a match occurs.

match() It searches a specified regular expression in a given string

and returns that regular expression if a match occurs.

replace() It replaces a given string with the specified replacement.

substr() It is used to fetch the part of the given string on the basis

of the specified starting position and length.

substring() It is used to fetch the part of the given string on the basis

of the specified index.

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
44

slice() It is used to fetch the part of the given string. It allows us

to assign positive as well negative index.

toLowerCase() It converts the given string into lowercase letter.

toLocaleLowerCase() It converts the given string into lowercase letter on the

basis of host?s current locale.

toUpperCase() It converts the given string into uppercase letter.

toLocaleUpperCase() It converts the given string into uppercase letter on the

basis of host?s current locale.

toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.

split() It splits a string into substring array, then returns that

newly created array.

trim() It trims the white space from the left and right side of the

string.

Console.log():
`console.log()` is a function used in JavaScript to output data to the console,
typically in a web browser's developer tools console or in a Node.js environment.
It is commonly used for debugging purposes or for providing feedback to
developers about the state of their code.

Here's a basic explanation of how it works:

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
45

1.console: This is the global object in JavaScript that provides access to the
browser's debugging console. It has various methods for logging different types
of information.

2. log(): This is a method of the `console` object. It is used to log messages,


variables, or any other data to the console.

For example, you can use `console.log()` to print a message to the console:

console.log("Hello, world!");

You can also log variables:

let num = 10;


console.log(num); // Outputs: 10

`console.log()` can also log multiple values separated by commas:

let firstName = "John";


let lastName = "Doe";
console.log("Name:", firstName, lastName); // Outputs: Name: John Doe

Additionally, `console.log()` can log objects, arrays, and other complex data
structures, providing a detailed representation of their contents.

let person = { name: "Alice", age: 30 };


console.log(person); // Outputs: { name: 'Alice', age: 30 }

Overall, `console.log()` is an essential tool for developers when debugging


JavaScript code, as it allows them to inspect the values of variables and track the
flow of their programs by outputting messages to the console.

Regular Expression (regex) pattern matching in


JavaScript

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
46

Regular Expression (regex) pattern matching in JavaScript allows you to search


for patterns within strings and manipulate text based on those patterns. Regular
expressions are sequences of characters that define a search pattern, which can
include literals, character classes, quantifiers, anchors, and more. JavaScript
provides built-in support for regular expressions through the `RegExp` object and
related methods.

Regular Expression Pattern Matching in JavaScript:

1. Creating Regular Expressions:


Regular expressions in JavaScript can be created using the `RegExp`
constructor or by using the regex literal notation enclosed in forward slashes
(`/pattern/`).

For example:

var pattern1 = new RegExp('pattern');


(or)
var pattern2 = /pattern/;

2. Searching for Patterns:


Regular expressions can be used with the `test()` method or the `match()`
method of the string object to search for patterns within strings. The `test()`
method returns a boolean indicating whether the pattern matches the string,
while the `match()` method returns an array of matches.

For example:

var str = 'The quick brown fox jumps over the lazy dog';
var pattern = /fox/;

var isMatch = pattern.test(str); // true


var matches = str.match(pattern); // ['fox']

3. Modifiers and Flags:


Regular expressions can have modifiers (flags) that control the behavior of the
pattern matching. Common modifiers include `i` (case-insensitive), `g` (global
match), `m` (multiline match), and `u` (unicode).

For example:
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
47

var str = 'The quick brown Fox jumps over the lazy Dog';
var pattern = /fox/i; // Case-insensitive match

var matches = str.match(pattern); // ['Fox']

4. Common Patterns:
Regular expressions can match common patterns such as character classes
(`[a-z]`, `\d`, `\w`), quantifiers (`+`, `*`, `{n}`, `{n,m}`), anchors (`^`, `$`), and
groups (`()`).

For example:

var str = '123-456-7890';


var pattern = /\d{3}-\d{3}-\d{4}/; // Match phone
number pattern
var isMatch = pattern.test(str); // true

Character Classes ([a-z], \d, \w):

● [a-z]: Matches any lowercase letter from 'a' to 'z'.


● \d: Matches any digit character.
● \w: Matches any word character (alphanumeric character
plus underscore).

Quantifiers (+, *, {n}, {n,m}):

● +: Matches the preceding element one or more times.


● *: Matches the preceding element zero or more times.
● {n}: Matches the preceding element exactly n times.
● {n,m}: Matches the preceding element at least n times,
but no more than m times.

Anchors (^, $):

● ^: Matches the beginning of a string.


● $: Matches the end of a string.

Groups (()) and Capture Groups:

● (): Groups multiple tokens together.


____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
48

Example:

// Regular expression to match a word starting with a vowel


//and ending with a digit

<script>

const regex = /^([aeiou]\w+)\d$/;

// Test strings
const testStrings = ["apple5", "banana12", "3orange"];

// Test the regular expression against each string

for(i=0;i<testStrings.length;i++)
{

if (regex.test(testStrings[i]))
{
console.log(testStrings[i]," matches the pattern.");
}
else
{
console.log(testStrings[i]," does not match the
pattern.");
}
}

</script>

Output (@Console):

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
49

In this example:

● ^([aeiou]\w+)\d$ is the regular expression.


● ^ and $ are anchors.
● ([aeiou]\w+) is a group that matches a word starting
with a vowel.
● \d matches a digit at the end of the string.

5. Replacement and Manipulation:


Regular expressions can be used with the `replace()` method of the string object
to replace matched patterns with new strings.

For example:

var str = 'Hello, World!';


var pattern = /world/i;

var newStr = str.replace(pattern, 'Universe'); //


document.write(newStr);//'Hello, Universe!'

Here's a program demonstrating pattern matching using regular expressions in


JavaScript:

<script>

var str = 'The quick brown fox jumps over the lazy dog';
var pattern = /fox/;

var isMatch = pattern.test(str); // true


var matches = str.match(pattern); // ['fox']

console.log(isMatch); // Output: true


console.log(matches); // Output: ['fox']

</script>

In this program, the regular expression `/fox/` is used to search for the pattern
"fox" within the string `str`. The `test()` method returns `true` indicating that the

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
50

pattern exists in the string, and the `match()` method returns an array containing
the matched substring "fox".

JavaScript Objects

Objects creation:
In JavaScript, objects can be created using different methods, including object
literals, constructor functions, the Object.create() method, and ES6
classes. Let's explore each method:

1. Object Literals: The simplest way to create an object in JavaScript is using


object literals { }. Object literals allow you to define key-value pairs within curly
braces.

// Object literal
let person = {
name: 'John',
age: 30,
city: 'New York'
};
//object literal using const with an object literal.
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
salary: 25000
};

Note:
1. It is a common practice to declare objects with the const keyword.
2. The object is declared using let, which means its reference can be
reassigned to a different object later in the code.
3. The object is declared using const, which means its reference cannot
be reassigned to a different object after initialization. However, the
properties of the object can still be modified.

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
51

2. Constructor Functions: Constructor functions are traditional functions used to


create objects. They are invoked with the new keyword and typically initialize object
properties using the ‘this’ keyword.

// Constructor function
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}

// Creating objects using constructor function


let person1 = new Person('John', 30, 'New York');
let person2 = new Person('Jane', 25, 'Los Angeles');

3. Object.create() Method: The Object.create() method creates a new object with the
specified prototype object and properties.

// Prototype object
let personPrototype = {
greet: function() {
return 'Hello, my name is ' + this.name;
}
};

// Creating object using Object.create()


let person = Object.create(personPrototype);
person.name = 'John';
person.age = 30;
person.city = 'New York';

4. ES6 Classes: With the introduction of ES6, JavaScript supports class syntax for
defining objects and their behavior.

// ES6 class
class Person {
constructor(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
52

greet() {
return 'Hello, my name is ' + this.name;
}
}

// Creating object using class syntax


let person = new Person('John', 30, 'New York');

Each method has its advantages and use cases.

● Object literals are simple and straightforward for


creating single instances of objects.
● Constructor functions are useful for creating multiple
instances with shared behavior.
● Object.create() is useful when you want to create
objects with specific prototypes.
● ES6 classes provide syntactic sugar for constructor
functions and are recommended for defining object
blueprints in modern JavaScript.

Object Modification:

Objects in JavaScript are mutable, which means you can modify their
properties and methods after creation.

// Modifying object properties


person.name = 'Jane';
person.age = 25;

// Adding new properties


person.email = 'jane@example.com';

// Modifying object methods


person.greet = function() {
return 'Hi, I am ' + this.name;
};

Additionally, you can also use methods like Object.assign() and object spread
syntax (...) to modify objects by merging properties from multiple sources.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
53

// Modifying object using Object.assign()


let newPerson = Object.assign({}, person, { age: 35 });

// Modifying object using object spread syntax


let updatedPerson = { ...person, age: 35 };

this Keyword
In JavaScript, the this keyword refers to an object.

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is


used:

● In an object method, this refers to the object.

● Alone, this refers to the global object.

● In a function, this refers to the global object.

● In a function, in strict mode, this is undefined.

● In an event, this refers to the element that received the event.

● Methods like call(), apply(), and bind() can refer this to any
object.

Example:The ‘this’ keyword behaves in different contexts in JavaScript.

1. In an object method: `this` refers to the object itself.


const obj = {
property: 'value',
method: function() {
console.log(this.property); // 'value'
}
};

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
54

obj.method();

2. Alone or in a function in non-strict mode: `this` refers to the global object


(`window` in browsers, `global` in Node.js).

console.log(this === window); // true


function globalFunction() {
console.log(this === window); // true
}
globalFunction();

3. In a function in strict mode: `this` is `undefined`.

function strictFunction() {
console.log(this === undefined); // true
}
strictFunction();

4. In an event: `this` refers to the element that received the event.

<button onclick="console.log(this)">Click me</button>

5. Methods like `call()`, `apply()`, and `bind()`: These methods can explicitly set
`this` to refer to any object.

function greet() {
console.log(`Hello, ${this.name}`);
}
const person = { name: 'Alice' };
greet.call(person); // 'Hello, Alice'

Understanding the behavior of `this` in different contexts is crucial for writing


effective JavaScript code.

Note: this is not a variable. It is a keyword. You cannot change the value of
this.

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
55

getElementById():
`getElementById()` is a method in JavaScript used to retrieve an HTML element
from the document by its unique identifier (ID). Here's an explanation of how it
works:

Syntax:

document.getElementById(elementId)

→ Parameters:`elementId`: A string representing the unique ID of the element


you want to retrieve.

→ Return Value: The method returns a reference to the first element in the
document with the specified ID. If no element with the specified ID exists, `null` is
returned.

→Usage:This method is typically used to access and manipulate specific


elements in the HTML document based on their unique IDs.

Example:

<!DOCTYPE html>
<html>
<head>
<title>getElementById Example</title>
</head>
<body>
<div id="exampleDiv">This is a div element with ID "exampleDiv".</div>
<script>
// Retrieving the element with ID "exampleDiv"
var element = document.getElementById("exampleDiv");

// Modifying the content of the retrieved element


element.innerHTML = "This content has been changed using JavaScript.";
</script>
</body>
</html>

In this example:

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
56

The `getElementById()` method is used to retrieve the `<div>` element with the
ID "exampleDiv".

The retrieved element is then modified using the `innerHTML` property to change
its content.

innerHTML:
innerHTML is a property commonly used in web development when working
with HTML elements through JavaScript. It represents the HTML content within
an element. When you access or modify the innerHTML property of a DOM
(Document Object Model) element, you are essentially accessing or modifying
the HTML markup inside that element.

Here's a brief explanation of how innerHTML works:

1. Accessing innerHTML: You can access the innerHTML property of an


HTML element using JavaScript. For example:
var element = document.getElementById("exampleElement");

var htmlContent = element.innerHTML;

In this code snippet, element is a reference to an HTML element, and


innerHTML retrieves the HTML content inside that element.

2. Modifying innerHTML: You can also modify the HTML content of an


element by assigning new HTML markup to its innerHTML property. For
example:
var element = document.getElementById("exampleElement");

element.innerHTML = "<p>New HTML content</p>";

In this code snippet, the HTML content inside the element with the ID
"exampleElement" is replaced with the new HTML markup specified

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
57

Overall, innerHTML provides a convenient way to access and manipulate the


HTML content of an element within a web page using JavaScript.

Taking input from the user on a web page

There are several ways to take input from the user on a web page. Here are two
common methods:

1. HTML Form Elements:


○ HTML provides various form elements such as <input>, <textarea>,
<select>, <button>, etc., which allow users to input data.
○ Example:

<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<input type="submit" value="Submit">
</form>

When the form is submitted, the data entered by the user is sent to the server for
processing.

2. JavaScript Prompts:

● JavaScript provides a built-in prompt() function that displays a dialog box with a
message to the user, prompting them to input data.
● Example:

var userInput = prompt("Please enter your name:");

The value entered by the user is stored in the variable userInput and can be used in the
JavaScript code.

Note: JavaScript prompts are synchronous and block the execution of further JavaScript
until the user responds.

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
58

Validating User Input with JavaScrip /


JavaScript Form Validation

It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is a must to authenticate users.

JavaScript provides a facility to validate the form on the client-side so data processing
will be faster than server-side validation. Most web developers prefer JavaScript form
validation.

Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.

Example:
Program to validate the password length must be greater than 8 characters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div style="text-align:center;background-color:#00f; margin:
100px;" >
<br><br>
<h2 >Login Page</h2>
<label for="name" >User name </label>
<input type="text" id="name" placeholder="Enter user
name" >
<br><br>
<label for="pwd" >Password</label>
<input type="password" id="pwd" placeholder="Enter
password" >

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
59

<br><br>
<input type="submit" value="Login"
onclick="pwdlength()">
<br><br>
</div>
<script>

function pwdlength()
{
const passwordInput =
document.getElementById('pwd');
const password = passwordInput.value;
if (password.length <= 8)
{
alert('Password must be greater than 8
characters');
passwordInput.focus(); // Focus on the password
field
return false; // Stop further processing
}
}
</script>
</body>
</html>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
60

Output

Write a program to read the two no.s using prompt, do


the addition and subtraction on button click and
display the output as alert.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
61

</head>
<body>
<form>
<label for="n1">Num1</label>
<input type="text" id="n1" placeholder="Enter num1">
<br> <br>
<label for="n2">Num2</label>
<input type="text" id="n2" placeholder="Enter num2">
<br><br>
<input type="button" value="Add" onclick="add()">
<input type="button" value="sub" onclick="sub()">
</form>
<script>
//self invoking function
(function(){alert("Auto Invoked Function");})();
//event occurs
function add()
{
var
num1=parseInt(document.getElementById("n1").value);
var
num2=parseInt(document.getElementById("n2").value);
var sum=num1+num2;
alert("addition :"+sum);
}
function sub()
{
var
num1=parseInt(document.getElementById("n1").value);
var
num2=parseInt(document.getElementById("n2").value);
var sub=num1-num2;
alert("subtraction :"+sub);
}
//

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
62

function show()
{
alert("hi");
}
show();
</script>

</body>
</html>

Output

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
63

____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology

You might also like