0% found this document useful (0 votes)
2 views58 pages

Unit 4 Java Script

JavaScript is a lightweight, cross-platform programming language used for both client-side and server-side development, with syntax influenced by Java and C. It allows for dynamic web content, form validation, and can be included in HTML via internal or external scripts. While it offers advantages like reduced server interaction and immediate feedback, it has limitations such as lack of file handling and multi-threading capabilities.

Uploaded by

tanmayi.cs22
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)
2 views58 pages

Unit 4 Java Script

JavaScript is a lightweight, cross-platform programming language used for both client-side and server-side development, with syntax influenced by Java and C. It allows for dynamic web content, form validation, and can be included in HTML via internal or external scripts. While it offers advantages like reduced server interaction and immediate feedback, it has limitations such as lack of file handling and multi-threading capabilities.

Uploaded by

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

UNIT-4

JavaScript
Overview of JavaScript
JavaScript is a lightweight, cross-platform, and interpreted compiled programming language
which is also known as the scripting language for webpages. Its syntax is based on the Java
and C languages — many structures from those languages apply to JavaScript as well.
JavaScript can be used for Client-side developments as well as Server-side developments.
Javascript is both imperative and declarative type of language. JavaScript contains a standard
library of objects, like Array, Date, and Math, and a core set of language elements
like operators, control structures, and statements.

● Client-side: It supplies objects to control a browser and its Document Object Model
(DOM). Like if client-side extensions allow an application to place elements on an HTML
form and respond to user events such as mouse clicks, form input, and page navigation.
● Server-side: It supplies objects relevant to running JavaScript on a server. Like if the
server-side extensions allow an application to communicate with a database, and provide
continuity of information from one invocation to another of the application, or perform file
manipulations on a server.
● Imperative language – imperative code focuses on writing an explicit sequence of
commands to describe how you want the computer to do things.
● Declarative programming – declarative code focuses on specifying the result of what
you want. Developers are more concerned with the answer that is received. It declares what
kind of results we want and leave programming language aside focusing on simply figuring
out how to produce them.

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


● Internal JS: We can add JavaScript directly to our HTML file by writing the code inside
the <script> tag. The <script> tag can either be placed inside the <head> or the <body> tag
according to the requirement.
● External JS: We can write JavaScript code in other file having an [Link] and then
link this file inside the <head> tag of the HTML file in which we want to add this code.
Syntax:
<script>
// JavaScript Code
</script>

Features of JavaScript:
Here are a few things that we can do with JavaScript:
● JavaScript was created in the first place for DOM manipulation. Earlier websites were
mostly static, after JS was created dynamic Web sites were made.
● Functions in JS are objects. They may have properties and methods just like another object.
They can be passed as arguments in other functions.
● Can handle date and time.
● Performs Form Validation although the forms are created using HTML.
● No compiler is needed.

Applications of JavaScript:
● Web Development: Adding interactivity and behavior to static sites
● Web Applications: With technology, browsers have improved to the extent that a language
was required to create robust web applications. When we explore a map in Google Maps
then we only need to click and drag the mouse. All detailed view is just a click away, and
this is possible only because of JavaScript. It uses Application Programming
Interfaces(APIs) that provide extra power to the code.
● Server Applications: With the help of [Link], JavaScript made its way from client to
server and [Link] is the most powerful on the server-side.
● Games: Not only in websites, but JavaScript also helps in creating games.
● Smartwatches: JavaScript is being used in all possible devices and applications. It
provides a library PebbleJS which is used in smartwatch applications. This framework
works for applications that require the internet for its functioning.
● Art: Artists and designers can create whatever they want using JavaScript to draw on
HTML 5 canvas.
● Machine Learning: This JavaScript [Link] library can be used in web development by
using machine learning.
● Mobile Applications: The features and uses of JavaScript make it a powerful tool for
creating mobile applications.
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.

Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included
in or referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact
with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid e-
mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.
The <script> tag
The <script> tag in HTML is used to define the client-side script.
The <script> tag contains the scripting statements, or it points to an external script file.
The JavaScript is mainly used in form validation, dynamic changes of content, image
manipulation, etc.
Syntax:
<script> Script Contents... </script>

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.
i.e., Specifies that the script is downloaded in parallel to parsing
the page, and executed as soon as it is available (before parsing
completes) (only for external scripts)

defer It is a boolean value which is used to indicate that script is


executed after document has been parsed.
i.e., Specifies that the script is downloaded in parallel to parsing
the page, and executed after the page has finished parsing (only
for external scripts)

The script tag can be used within <body> or <head> tag to embed the scripting code.
The browser loads all the scripts included in the <head> tag before loading and rendering
the <body> tag elements. So, always include JavaScript files/code in the <head> that are going
to be used while rendering the UI. All other scripts should be placed before the
ending </body> tag. This way, you can increase the page loading speed.

Example Program:
<html>
<body>
<script type="text/javascript">
[Link]("JavaScript is a simple language for javatpoint learners");
</script>
</body>
</html>
Output:

Let's see the example to have script tag within HTML head tag.
<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>
Output:

The script tag can be used to link external script file by src attribute. It must be used within the
<head> tag only. write JavaScript code in a separate file with .js extension and include it in a
web page using <script> tag and reference the file via src attribute.
Example Program:
[Link]
function msg(){
alert("Hello Javatpoint");
}
[Link]
<html>
<head>
<script type="text/javascript" src="[Link]"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body> </html>
General Syntactic Characteristics
● All JavaScript scripts will be embedded in HTML documents.
o Either directly, as in
<script type = "text/javaScript">
-- JavaScript script -
</script>
o Or indirectly, as a file specified in the src attribute of <script>, as in
<script type = "text/javaScript"
src = "[Link]">
</script>
● Language Basics:
o Identifier form: begin with a letter or underscore, followed by any number of letters,
underscores, and digits
o Javascript is case sensitive
o 25 reserved words, plus future reserved words Eg: break, continue, switch, case,
if, else, while, for….
o Comments: both // and /* ... */
● Scripts are usually hidden from browsers that do not include JavaScript interpreters by
putting them in special comments
<!--
-- JavaScript script -
//-->
o Also hides it from HTML validators
● Semicolons can be a problem
o They are "somewhat" optional.
o You can omit the semicolon between two statements if they are written on separate
lines.
o You can omit a semicolon at the end of a program or if the next token in the program
is a closing curly brace }.
o You should put each statement on its own line whenever possible and terminate each
statement with a semicolon.
Problem: When the end of the line may not be the end of a statement – JavaScript puts
a semicolon there. But this implicit insertion can lead to problems.
Eg: return
x;
The interpreter will insert a semicolon after return, because return need not be followed
by an expression, making x an invalid orphan.
To avoid this problem, put each statement on its own line and terminate each statement
with a semicolon.
When separated by semicolons, multiple statements on one line are allowed:
a = 5; b = 6; c = a + b;

Primitives

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and
has no methods or properties.

There are seven primitive data types:


● string
● number
● bigint
● boolean
● undefined
● symbol
● null

The typeof operator tells you what type a primitive value is. To get the current type of the value
that the variable stores, you use the typeof operator.

String:

● In JavaScript, a string is a sequence of zero or more characters. A string literal begins


and ends with either a single quote(') or a double quote (").

Example:
let greeting = 'Hi';
let message = "Bye";

● If you want to single quote or double quotes in a literal string, you need to use the
backslash to escape it.

For example:
let message = 'I\'m also a valid string'; // use \ to escape the single quote (')
● JavaScript strings are immutable. This means that it cannot be modified once created.
However, you can create a new string from an existing string.

For example:
let str = 'JavaScript';
str = str + ' String';

In this example:
● First, declare the str variable and initialize it to a string of 'JavaScript'.
● Second, use the + operator to combine 'JavaScript' with ' String' to make its
value as 'Javascript String'.

● Behind the scene, the JavaScript engine creates a new string that holds the new
string 'JavaScript String' and destroys the original strings 'JavaScript' and ' String'.

The following example attempts to change the first character of the string JavaScript:

let s = 'JavaScript';
s[0] = 'j';
[Link](s)

The output is:


'JavaScript'
because STRINGS ARE IMMUATBLE AND CANNOT
But not: BE CHANGED
'javaScript'

Number:

● JavaScript uses the number type to represent both integer and floating-point numbers
(decimals and exponentials).

● The following statement declares a variable and initializes its value with an integer:
let num = 100;

● To represent a floating-point number, you include a decimal point followed by at least


one number.

For example:
let price= 12.5;
let discount = 0.05;

Exponential number example:


let number3 = 3e5 // 3 * 10^5

● Note that JavaScript automatically converts a floating-point number into an integer


number if the number appears to be a whole number.

● The reason is that Javascript always wants to use less memory since a floating-point
value uses twice as much memory as an integer value.
For example:
let price = 200.00; // interpreted as an integer 200

● To get the range of the number type, you use


Number.MIN_VALUE and Number.MAX_VALUE.

For example:
[Link](Number.MAX_VALUE); // 1.7976931348623157e+308
[Link](Number.MIN_VALUE); // 5e-324

● A number type can also be +Infinity, -Infinity, and NaN (not a number).

For example,
const number1 = 3/0;
[Link](number1); // Infinity

const number2 = -3/0;


[Link](number2); // -Infinity

// strings can't be divided by numbers


const number3 = "abc"/3;
[Link](number3); // NaN

bigint:

● The bigint type represents the whole numbers that are larger than 253 – 1. To form
a bigint literal number, you append the letter n at the end of the number.
For Example:
1. let pageView = 9007199254740991n;
[Link](typeof(pageView)); // 'bigint'

2. // Adding two big integersOut


const result1 = value1 + 1n;
[Link](result1); // "900719925124740999n"

3. // Error! BitInt and number cannot be added


const result2 = value2 + 1;
[Link](result2);
Output:
900719925124740999n
Uncaught TypeError: Cannot mix BigInt and other types
Boolean:

● The boolean type has two literal values: true and false in lowercase. The following
example declares two variables that hold the boolean values.

let inProgress = true;


let completed = false;
[Link](typeof completed); // boolean [Link](typeof(completed));
● JavaScript allows values of other types to be converted into boolean values
of true or false. To convert a value of another data type into a boolean value, you use
the Boolean() function. The following table shows the conversion rules:

Type true false


string non-empty string empty string
number non-zero number and Infinity 0, NaN
object non-null object null
undefined undefined

For example:
[Link](Boolean('Hi'));// true
[Link](Boolean('')); // false
[Link](Boolean(20)); // true
[Link](Boolean(Infinity)); // true
[Link](Boolean(0)); // false
[Link](Boolean({foo: 100})); // true on non-empty object
[Link](Boolean(null));// false

Undefined:

● The undefined type is a primitive type that has only one value undefined.

● By default, when a variable is declared but not initialized, it is assigned the value
of undefined.

● Consider the following example:


let counter;
[Link](counter); // undefined
[Link](typeof counter); // undefined

In this example, the counter is a variable. Since counter hasn’t been initialized, it is
assigned the value undefined. The type of counter is also undefined.

● It’s important to note that the typeof operator also returns undefined when you call it
on a variable that hasn’t been declared:
Example: [Link](typeof undeclaredVar); // undefined
● It is also possible to explicitly assign a variable value undefined.
For example,
let name = undefined;
[Link](name); // undefined

● Note: It is recommended not to explicitly assign undefined to a variable.


Usually, null is used to assign 'unknown' or 'empty' value to a variable.

Symbol:

● Different from other primitive types, the symbol type does not have a literal form.
● A Symbol is a value created by invoking the Symbol function which is guaranteed to
create a unique value every time you call it.

● It takes one parameter, a string description, that will show up when you print the
symbol.
Example:
let x = Symbol("this is a symbol");
typeof x; // 'symbol'
[Link](Symbol() == Symbol()); // false

null:

● In JavaScript, null is a special value that represents empty or unknown value.

● The null type is the second primitive data type that also has only one value null.

For example,
let number = null;
[Link](typeof obj); // object

The code above suggests that the number variable is empty.

● Note: null is not the same as NULL or Null.

● JavaScript defines that null is equal to undefined as follows:


[Link](null == undefined); // true

Variables

Variables are containers for storing data (storing data values) that can be changed later on.

Declare a Variable

● In JavaScript, a variable can be declared using var, let, const keywords.


o var keyword is used to declare variables since JavaScript was created. It is
confusing and error-prone when using variables declared using var.
o let keyword removes the confusion and error of var. It is the new and
recommended way of declaring variables in JavaScript.
o const keyword is used to declare a constant variable that cannot be changed
once assigned a value.

● To declare a variable, write the keyword let followed by the name of the variable you
want to give, as shown below.
Example: Variable Declaration
let msg; // declaring a variable without assigning a value
In the above example, var msg; is a variable declaration. It does not have any value
yet.

● The default value of variables that do not have any value is undefined.

● You can assign a value to a variable using the = operator when you declare it or after
the declaration and before accessing it.
Example: Variable Initialization
let msg;
msg = "Hello JavaScript!"; // assigning a string value

In the above example, the msg variable is declared first and then assigned a string value
in the next line.

● You can declare a variable and assign a value to it in the same line. Values can be of
any datatype such as string, numeric, boolean, etc.
Example: Variable Declaration and Initialization
let name = "Steve"; //assigned string value
let num = 100; //assigned numeric value
let isActive = true; //assigned boolean value

● Multiple variables can be declared in a single line, as shown below.


Example: Multiple Variables
let name = "Steve", num = 100, isActive = true;

● You can copy the value of one variable to another variable, as shown below.
Example: Copy Variable
let num1 = 100;
let num2 = num1;

● JavaScript allows multiple white spaces and line breaks when you declare a variables.
Example: Whitespace and Line Breaks
let name = "Steve",
num = 100,
isActive = true;

● Variable names are case-sensitive in JavaScript. You cannot declare a duplicate


variable using the let keyword with the same name and case. JavaScript will throw a
syntax error. Although, variables can have the same name if declared with
the var keyword (this is why it is recommended to use let).

Example: Syntax Error


let num = 100;
let num = 200; //syntax error

var num = 100;


var num = 200; //Ok

The general rules for constructing names for variables (unique identifiers) are:
● Names can contain letters, digits, underscores, and dollar signs.
● Names must begin with a letter.
● Names can also begin with $ and _.
o These names are valid:
let $ = 1; // declared a variable with the name "$"
let _ = 2;
alert($ + _); // 3
● Names are case sensitive. So, the variable names msg, MSG, Msg, mSg are considered
separate variables.
● Reserved words (lik
● Dynamic Typinge JavaScript keywords) cannot be used as names.

● JavaScript is a loosely typed language. It means that you don't need to specify what
data type a variable will contain.

● You can update the value of any type after initialization. It is also called dynamic
typing.
Example: Loosely Typed Variable
let myvariable = 1; // numeric value
myvariable = 'one'; // string value
myvariable = 1.1; // decimal value
myvariable = true; // Boolean value
myvariable = null; // null value

Constant Variables in JavaScript

● Use const keyword to declare a constant variable in JavaScript.

● Constant variables must be declared and initialized at the same time.

● The value of the constant variables can't be changed after initialized them.

Example: Constant Variables


const num = 100;
num = 200; //error

const name; //error


name = "Steve";

● The value of a constant variable cannot be changed but the content of the value can be
changed. For example, if an object is assigned to a const variable then the underlying
value of an object can be changed.

Example: Constant Variables


const person = { name: 'Steve'};
[Link] = "Bill";
alert([Link]); //Bill

● It is best practice to give constant variable names in capital letters to separate them from
other non-constant variables.

Variable Scope

In JavaScript, a variable can be declared either in the global scope or the local scope.

Global Variables

Variables declared out of any function are called global variables. They can be accessed
anywhere in the JavaScript code, even inside any function.

Local Variables

Variables declared inside the function are called local variables of that function. They can only
be accessed in the function where they are declared but not outside.
The following example includes global and local variables.

Example: Global and Local Variable


let greet = "Hello " // global variable

function myfunction(){
let msg = "JavaScript!";
alert(greet + msg); //can access global and local variable
}

myfunction();

alert(greet);//can access global variable


alert(msg); //error: can't access local variable

Declare Variables without var and let Keywords

● Variables can be declared and initialized without the var or let keywords. However, a
value must be assigned to a variable declared without the var keyword.

● The variables declared without the var keyword become global variables, irrespective
of where they are declared.

● It is Recommended to declare variable using the let keyword.


Example: Variable Declaration Without var or let Keyword
function myfunction(){
msg = "Hello JavaScript!";
}

myfunction();
alert(msg); // msg becomes global variable so can be accessed here

Points to Remember:

1. Variables can be defined using let keyword. Variables defined


without let or var keyword become global variables.
2. Variables should be initialized before accessing it. Unassigned variable has
value undefined.
3. JavaScript is a loosely-typed language, so a variable can store any type value.
4. Variables can have local or global scope. Local variables cannot be accessed out of
the function where they are declared, whereas the global variables can be accessed
from anywhere.

Typeof operator

In JavaScript, the typeof operator returns the data type of its operand in the form of a string.
The operand can be any object, function, or variable.

Syntax:
typeof operand
OR
typeof (operand)

Note: Operand is an expression representing the object or primitive whose type is to be


returned.

Example:
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object"

let type;
type = typeof 'Hi';
[Link](type); // 'string'
we will pass numbers as operands and use the typeof operator and log the result to the console.
We will use a positive integer, negative integer, zero, floating-point number, infinity, NaN, and
Math equations as operands. We will also use the concept to explicitly typecasting and parsing
a string to an integer or float and use it as an operand.

Example:
[Link](typeof 12) //number
[Link](typeof -31) //number

JavaScript typeof operator & parentheses

When passing an expression to the typeof operator, you need to use parentheses.

For example:
let type = typeof (100 + '10');
[Link](type);

Output:
'string'
string concatenation
In this example, the expression 100 + '10' returns the string '10010'. Therefore, its type
is 'string'. If you don’t use the parentheses, you’ll get an unexpected result.

For example:
let type = typeof 100 + '10';
[Link](type);

Output:
'number10'
In this example, the typeof 100 returns 'number'. Therefore, the result is a string that is the
concatenation of the string 'number' and '10'.

JavaScript Operators and Expressions


Operators are used to assign values, compare values, perform arithmetic operations, and
more.

An expression is a combination of values, variables, and operators, which computes to a


value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
There are different types of JavaScript operators:

● Arithmetic Operators
● Assignment Operators
● Comparison Operators
● Logical Operators
● Conditional Operators
● Type Operators

i. Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y = 5, the table below explains the arithmetic operators:
ii. Assignment Operators
Assignment operators are used to assign values to JavaScript variables.

Given that x = 10 and y = 5, the table below explains the assignment operators:

const person = {
name: "John",
age: 30
};
iii. Comparison Operators
Comparison operators are used in logical statements to determine equality or difference
between variables or values.

Given that x = 5, the table below explains the comparison operators:

type is diff "5" is a string


iv. Conditional (Ternary) Operator
The conditional operator assigns a value to a variable based on a condition.

v. Logical Operators
Logical operators are used to determine the logic between variables or values.

Given that x = 6 and y = 3, the table below explains the logical operators:

vi. The typeof Operator


The typeof operator returns the type of a variable, object, function or expression:
Difference between == and === operator in JavaScript
Both double equals == and triple equals === operator is used for comparing between two
values on which the operator is used on.

The difference between the two operators is that the double equals == will compare the
values loosely, meaning that it will try to convert values with different types before
comparing them.

The triple equals === won’t convert values of different types. It will simply return false when
comparing values of different types.
To understand their differences, let’s try comparing two different values between the number
value 0 and boolean value false:

As you can see from the code above, the == operator returns true because the boolean value
false is converted to a number before comparing it with 0.
On the other hand, the triple equals === will simply return false for the same values as above
because it doesn’t do conversion at all.
Screen Output
JavaScript can "display" data in different ways:

● Writing into an HTML element, using innerHTML.


● Writing into the HTML output using [Link]().
● Writing into an alert box, using [Link]().
● Writing into the browser console, using [Link]().

i. Using innerHTML
To access an HTML element, JavaScript can use the [Link](id) method.

The id attribute defines the HTML element. The innerHTML property defines the HTML
content:

Example:

<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>

<p id="demo"></p>
<script>
[Link]("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

Output
ii. Using [Link]()
For testing purposes, it is convenient to use [Link]():
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<p>Never call [Link] after the document has finished loading.
It will overwrite the whole document.</p>

<script>

[Link](5 + 6);

</script>

</body>

</html>

Output

iii. Using [Link]()


You can use an alert box to display data:

<html>

<body>

<h2>My First Web Page</h2>

<p>My first paragraph.</p>


<script>

[Link](5 + 6);

</script>

</body>

</html>

Output prints on alert box

iv. Using [Link]()


For debugging purposes, you can call the [Link]() method in the browser to display data.

<html>
<body>
<h2>Activate Debugging</h2>
<p>F12 on your keyboard will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
Keyboard Input

The prompt() method in JavaScript is used to display a prompt box that prompts the user for
the input. It is generally used to take the input from the user before entering the page. It can be
written without using the window prefix. When the prompt box pops up, we have to click "OK"
or "Cancel" to proceed.

The box is displayed using the prompt() method, which takes two arguments: The first
argument is the label which displays in the text box, and the second argument is the default
string, which displays in the textbox. The prompt box consists of two buttons, OK and Cancel.
It returns null or the string entered by the user. When the user clicks "OK," the box returns the
input value. Otherwise, it returns null on clicking "Cancel". [Link]
Label (First Argument): This is the text or label that is displayed in the
box. It typically serves as an instruction or a prompt to inform the
user about what kind of input is expected. For example, if you want the
user to enter their name, you might set the label as "Please enter your
name."
Syntax
b. Default String (Second Argument): This is the default value or text that
prompt(message, default) is initially displayed in the input field of the dialog box. It serves as a
placeholder or suggestion for what the user can enter. If the user doesn't
change this default value and directly clicks "OK" or presses Enter, this
default string will be returned as the result.
message: It is an optional parameter. It is the text displays to the user. We can omit this value
if we don't require to show anything in the prompt.

default: It is also an optional parameter. It is a string that contains the default value displayed
in the textbox.

<html>
<head>
<script type = "text/javascript">
function fun() { default
prompt ("This is a prompt box", "Hello world");
} message
</script>
</head>
<body>
<p> Click the following button to see the effect </p>
<form>
<input type = "button" value = "Click me" onclick = "fun();" />
</form>
</body>
</html>

message argument

default argument
The prompt box takes the focus and forces the user to read the specified message. So, it should avoid
overusing this method because it stops the user from accessing the other parts of the webpage until the
box is closed.

Keyboard Events

i. onkeydown Event
The onkeydown event occurs when the user presses a key on the keyboard.

ii. onkeypress Event


The onkeypress event occurs when the user presses a key on the keyboard.

iii. onkeyup Event


The onkeyup event occurs when the user releases a key on the keyboard.
Arrays
An array is a special variable, which can hold more than one value.
If you have a list of items (a list of car names, for example), storing the cars in single variables could
look like this:

let car1 = "Saab";


let car2 = "Volvo";
let car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not
3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an
index number.
Using an array literal is the easiest way to create a JavaScript Array.

const array_name = [item1, item2, ...];

It is a common practice to declare arrays with the const keyword.

const cars = ["Saab", "Volvo", "BMW"];


Spaces and line breaks are not important. A declaration can span multiple lines:

const cars = [
"Saab",
"Volvo",
"BMW"
];
You can also create an array, and then provide the elements:
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
Accessing Array Elements
You access an array element by referring to the index number:

const cars = ["Saab", "Volvo", "BMW"];


let car = cars[0];

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an Array Element

Example
const cars = ["Saab", "Volvo", "BMW"];

cars[0] = "Opel";

JavaScript Maps
like dictionary?

A Map holds key-value pairs where the keys can be any datatype.

A Map remembers the original insertion order of the keys.

Essential Map Methods


How to Create a Map
You can create a JavaScript Map by:

● Passing an Array to new Map()


● Create a Map and use [Link]()

1. The new Map() Method

You can create a Map by passing an Array to the new Map() constructor:

Example:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Creating a Map from an Array:</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
[Link]("demo").innerHTML = [Link]("apples");
</script>
</body>
</html>

Output:
2. The set() Method

You can add elements to a Map with the set() method:

Example:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Using [Link]():</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map();
// Set Map Values
[Link]("apples", 500);
[Link]("bananas", 300);
[Link]("oranges", 200);
[Link]("demo").innerHTML = [Link]("apples");
</script>
</body>
</html>

Output:

The set() method can also be used to change existing Map values:

Example:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Using [Link]():</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
[Link]("apples", 200);
[Link]("demo").innerHTML = [Link]("apples");
</script>
</body>
</html>

Output:

3. The get() Method

The get() method gets the value of a key in a Map:


Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Using [Link]():</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
[Link]("demo").innerHTML = [Link]("apples");
</script>
</body>
</html>

Output:
4. The size Property

The size property returns the number of elements in a Map:

Example:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Maps</h2>
<p>Using [Link]:</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
[Link]("demo").innerHTML = [Link];
</script>
</body>
</html>

Output:

5. The delete() Method

The delete() method removes a Map element:


Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Maps</h2>
<p>Deleting Map elements:</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
// Delete an Element
[Link]("apples"); always use key
[Link]("demo").innerHTML = [Link];
</script>
</body>
</html>

Output:

6. The has() Method

The has() method returns true if a key exists in a Map:

Example:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Maps</h2>
<p>Using [Link]():</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
[Link]("demo").innerHTML = [Link]("apples");
</script>
</body>
</html>

Output:

7. The forEach() Method

The forEach() method calls a function for each key/value pair in a Map:

Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Using [Link]():</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
let text = "";
[Link] (function(value, key) {
text += key + ' = ' + value + "<br>"
})
[Link]("demo").innerHTML = text;
</script>
</body>
</html>

Output:
8. The entries() Method

The entries() method returns an iterator object with the [key, values] in a Map:

Example:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Using [Link]():</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
let text = "";
for (const x of [Link]()) {
text += x + "<br>";
}
[Link]("demo").innerHTML = text;
</script>
</body>
</html>

Output:
Javascript control statements:
1. If Statement

2. If else statement

3. if else if statement

JavaScript If Statement:
If statement is used to execute a block of statements if specified condition is true.

Syntax:

if(condition)

//Block of JavaScript statements.

JavaScript If Else Statement:


If else statement is used to execute either of two block of statements depends upon the
condition. If condition is true then if block will execute otherwise else block will execute.

Syntax:

if(condition)
{
//Block of JavaScript statements1.
}
else
{
//Block of JavaScript statements2.
}
JavaScript If Else If Statement:
If else statement is used to execute one block of statements from many depends upon the
condition. If condition1 is true then block of statements1 will be executed, else if condition2
is true block of statements2 is executed and so on. If no condition is true, then else block of
statements will be executed.

Syntax:

if(condition 1)
{
//Block of JavaScript statements1.
}
else if(condition 2)
{
//Block of JavaScript statements2.
}...
else if(condition n)
{
//Block of JavaScript statementsn.
}
else
{
//Block of JavaScript statements.
}

Example

<html>
<head>
<script>
var num=2;
if(num==1){
[Link]("JavaScript Statement 1");
}
else if(num==2){
[Link]("JavaScript Statement 2");
}
else if(num==3){
[Link]("JavaScript Statement 3");
}
else{
[Link]("JavaScript Statement n");
}
</script>
</head>
<body>
</body>
</html>

Output:
JavaScript Statement 2

Strings
JavaScript strings are for storing and manipulating text.
A JavaScript string is zero or more characters written inside quotes.
Example

let text = "John Doe";

You can use single or double quotes:

Example
let carName1 = "Volvo XC60"; // Double quotes
let carName2 = 'Volvo XC60'; // Single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding
the string:

Example

let answer1 = "It's alright";

let answer2 = "He is called 'Johnny'";

let answer3 = 'He is called "Johnny"';

String Methods
● String length
● String slice()
● String substring()
● String substr()
● String replace()
● String replaceAll()
● String toUpperCase()
● String toLowerCase()
● String concat()
● String trim()
● String trimStart()
● String trimEnd()
● String padStart()
● String padEnd()
● String charAt()
● String charCodeAt()
● String split()

String Length
The length property returns the length of a string:

let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

let length = [Link];

Output: 26
String slice()
slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: start position, and end position

Example

Slice out a portion of a string from position 7 to position 13:

let text = "Apple, Banana, Kiwi";


let part = [Link](7, 13); 13 not inclusive

Output: Banana

JavaScript counts positions from zero.

First position is 0.

Second position is 1

String substring()
substring() is similar to slice().

The difference is that start and end values less than 0 are treated as 0 in substring().

Example

let str = "Apple, Banana, Kiwi";

let part = [Link](7, 13);

Output: Banana

If you omit the second parameter, substring() will slice out the rest of the string.

String substr()
substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.
Example

let str = "Apple, Banana, Kiwi";

let part = [Link](7, 6);

Output: Banana

If you omit the second parameter, substr() will slice out the rest of the string.

let str = "Apple, Banana, Kiwi";

let part = [Link](7);

Output: Banana, Kiwi

If the first parameter is negative, the position counts from the end of the string.

Example

let str = "Apple, Banana, Kiwi";

let part = [Link](-4);

Output: Kiwi

Replacing String Content


The replace() method replaces a specified value with another value in a string:

Example

let text = "Please visit Microsoft!";

let newText = [Link]("Microsoft", "W3Schools");

Output: Please visit W3Schools

By default, the replace() method replaces only the first match:

Example

let text = "Please visit Microsoft and Microsoft!";


let newText = [Link]("Microsoft", "W3Schools");

Output: Please visit W3Schools and Microsoft!


By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-
case) will not work:

Example

let text = "Please visit Microsoft!";

let newText = [Link]("MICROSOFT", "W3Schools");

Output: Please visit Microsoft!

To replace case insensitive, use a regular expression with an /i flag (insensitive):

Example let text = "Please visit Microsoft and micROSOFT!";


let newText = [Link](/MICROSOFT/ig, "W3Schools");
[Link](newText);
let text = "Please visit Microsoft!";

let newText = [Link](/MICROSOFT/i, "W3Schools");

Output: Please visit W3Schools!

To replace all matches, use a regular expression with a /g flag (global match):

Example

let text = "Please visit Microsoft and Microsoft!";

let newText = [Link](/Microsoft/g, "W3Schools");

Output: Please visit W3Schools and W3Schools!

JavaScript String ReplaceAll()


The replaceAll() method allows you to specify a regular expression instead of a string to
be replaced.
If the parameter is a regular expression, the global flag (g) must be set, otherwise a
TypeError is thrown.
let name="tanmayi s balija"

let len=[Link];
Example [Link](len);

let slice=[Link](0,3);
[Link](slice);
text = [Link](/Cats/g,"Dogs");
let subs=[Link](5);//from 5th position everything
[Link](subs);
text = [Link](/cats/g,"dogs");
let subss=[Link](5,7);//from 5th position everything till 7th position
[Link](subss);

let substr=[Link](0,7);//from 0 seven characters


[Link](substr);

let substr1=[Link](0);//from 0 everything


String toUpperCase() [Link](substr1);

let substr2=[Link](-5,8);//backward
[Link](substr2);
Example let substr3=[Link](-9,10);
[Link](substr3);

let text1 = "Hello World!"; let repl1=[Link]("tan","chin");


[Link](repl1);

let n1="please visit word and office!"


let text2 = [Link](); let repl2=[Link]("word","sheet");
[Link](repl2);

let n2="please visit office and office!"


Output: HELLO WORLD! let repl3=[Link]("office","ppt");//by default it only replaces the firts occurence of the
string
[Link](repl3);

let n3="please visit word and office!"


let repl4=[Link](/WORD/i,"docs");//to make case insesitve
[Link](repl4);

String toLowerCase() let n4="please visit office and office!"


let repl5=[Link](/office/g,"ppt");//all occurences of office are replaced
[Link](repl5);

let text1 = "Hello World!"; let ucase=[Link]();


[Link](ucase);

let lcase=[Link]();
let text2 = [Link](); [Link](lcase);

let name1="tanmayi";
let name2="s balija";
Output: hello world! let conact=[Link](" ",name2);
let conact1=[Link](name2);
[Link](conact);
[Link](conact1);

String concat()
concat() joins two or more strings:

Example

let text1 = "Hello";

let text2 = "World";

let text3 = [Link](" ", text2);


Output: Hello World

String trim()
The trim() method removes whitespace from both sides of a string:

Example

let text1 = " Hello World! ";

let text2 = [Link]();

Output:

Length text1 = 22

Length text2 = 12

String trimStart()
The trimStart() method works like trim(), but removes whitespace only from the start
of a string.

Example

let text1 = " Hello World! ";

let text2 = [Link]();

Output:

Length text1 = 22

Length text2 = 17

String trimEnd()
The trimEnd() method works like trim(), but removes whitespace only from the end of a
string.
Example

let text1 = " Hello World! ";

let text2 = [Link]();

Output:

Length text1 = 22

Length text2 = 17

String padStart()
The padStart() method pads a string with another string:

Example

let text = "5";

let padded = [Link](4,"x");

Output:

xxx5
Example

let text = "5";

let padded = [Link](4,"0");

Output:

0005

String padEnd()
The padEnd() method pads a string with another string:
Example

let text = "5";

let padded = [Link](4,"x");

Output: 5xxx

String charAt()
The charAt() method returns the character at a specified index (position) in a
string:

Example

let text = "HELLO WORLD";

let char = [Link](0);

Output: H

String charCodeAt()
The charCodeAt() method returns the unicode of the character at a specified index
in a string:

The method returns a UTF-16 code (an integer between 0 and 65535).

Example

let text = "HELLO WORLD";

let char = [Link](0);

Output: 72

JavaScript Objects
diff btw object and variable

We know that JavaScript variables are containers for data values.

This code assigns a simple value (Fiat) to a variable named car:

let car = "Fiat";

Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to a variable named car:

const car = {type:"Fiat", model:"500", color:"white"};

The values are written as name:value pairs (name and value separated by a colon).

Object Definition
You define (and create) a JavaScript object with an object literal:

Example

const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Spaces and line breaks are not important. An object definition can span multiple lines:

Example

const person = {

firstName: "John",

lastName: "Doe",

age: 50,

eyeColor: "blue"

};

Object Properties
The name:values pairs in JavaScript objects are called properties:
Accessing Object Properties
You can access object properties in two ways:

[Link]

Example:

[Link];

OR

objectName["propertyName"]

Example:

person["lastName"];

Object Methods
Objects can also have methods.

Methods are actions that can be performed on objects.

Methods are stored in properties as function definitions.


Example

const person = {

firstName: "John",

lastName : "Doe",

id : 5566,

fullName : function() {

return [Link] + " " + [Link];

};

In the example above, this refers to the person object.

I.E. [Link] means the firstName property of this.

I.E. [Link] means the firstName property of person.

Accessing Object Methods


You access an object method with the following syntax:

[Link]()
Example

name = [Link]();

JavaScript Regular Expressions


A regular expression is a sequence of characters that forms a search pattern.

When you search for data in a text, you can use this search pattern to describe what
you are searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace
operations.

Syntax

/pattern/modifiers;

Example

/w3schools/i;

here,

/w3schools/i is a regular expression.

w3schools is a pattern (to be used in a search).

i is a modifier (modifies the search to be case-insensitive).

Using String Methods


In JavaScript, regular expressions are often used with the two string methods: search()
and replace().

The search() method uses an expression to search for a match, and returns the position
of the match.
The replace() method returns a modified string where the pattern is replaced.

Using String search() With a String


The search() method searches a string for a specified value and returns the position of
the match:

Example

Use a string to do a search for "W3schools" in a string:

let text = "Visit W3Schools!";

let n = [Link]("W3Schools");

The result in n will be:

Using String search() With a Regular


Expression
Example

Use a regular expression to do a case-insensitive search for "w3schools" in a string:

let text = "Visit W3Schools";

let n = [Link](/w3schools/i);

The result in n will be:

Using String replace() With a String


The replace() method replaces a specified value with another value in a string:
let text = "Visit Microsoft!";

let result = [Link]("Microsoft", "W3Schools");

Use String replace() With a Regular


Expression
Example

Use a case insensitive regular expression to replace Microsoft with W3Schools in a


string:

let text = "Visit Microsoft!";

let result = [Link](/microsoft/i, "W3Schools");

The result will be:

Visit W3Schools!

Regular Expression Modifiers


Regular Expression Patterns
Brackets are used to find a range of characters:

Metacharacters are characters with a special meaning:

Quantifiers define quantities:


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

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":
Example
Calculate the product of two numbers, and return the result:
let x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}

The result in x will be:


12

Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables can only be accessed from within the function.
Example

// code here can NOT use carName

function myFunction() {

let carName = "Volvo";

// code here CAN use carName

// code here can NOT use carName

Since local variables are only recognized inside their functions, variables with the
same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is
completed.
Window Object

• The window object in JavaScript corresponds to the browser itself.

• Window is the object of browser, it is not the object of javascript.

• Through it, you can access the current page’s URL, the browser’s history, and what’s
being displayed in the status bar, as well as opening new browser windows.

• An object of window is created automatically by the browser.

• the alert() function is actually a method of the window object.

Method Description

alert() displays the alert box containing message with ok button.

confirm() displays the confirm dialog box containing message with ok and cancel
button.
prompt() displays a dialog box to get input from the user.

open() opens the new window.

close() closes the current window.

setTimeout() performs action after specified time like calling function, evaluating
expressions etc.
Example program

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function input()
{
[Link]("BMS College of Engineering, Bangalore");
alert("Welcome to BMSCE");
var registration=confirm("Do You want to register for 3rd Sem ?");
if(registration)
{
var name=prompt("Enter your name:");
if(name=="CPN")
{
alert("CPN");
}
else
{
alert("You are not CPN");
}
}
else
alert("Please Register later");
}

setTimeout(function(){
[Link]("Tutorix is the best e-learning platform");
}, 2000);
[Link]("[Link]

function openWin() {
myWindow = [Link]("[Link] "_blank", "width=200,
height=100");
}
openWin();
function closeWin() {
[Link]();
}
closeWin();

input();
</script>
</body>
</html>

The Document Object Model (DOM)


• JavaScript is used to interact with the HTML document in which it is contained.
• This is accomplished through a programming interface (API) called the Document
Object Model.
• According to the W3C, the DOM is a:
Platform- and language-neutral interface that will allow programs and scripts to
dynamically access and update the content, structure and style of documents.
DOM Tree

DOM Nodes
• In DOM Tree the root or topmost object is called the Document Root.
• Each element within the HTML document is called a node. If the DOM is a tree, then
each node is an individual branch.
• There are:
1) Element nodes,
2) Text nodes,
3) Attribute nodes
Document Object
• The DOM document object is the root JavaScript object representing the entire
HTML document.
• It contains some properties and methods that we will use extensively in development
and is globally accessible as document.
• Accessing the properties is done through the dot notation.

Some Essential Document Object Methods

getElementById(“Id”)
getElementByClassName(“name”)
getElementByTagName(“name”)

You might also like