Module 2 Javascript (1)
Module 2 Javascript (1)
Unit II
Javascript: Introduction, Client side programming, script tag, comments, variables. Including JavaScript in
HTML: head, body, external. Data types. Operators: Arithmetic, Assignment, Relational, Logical.
Conditional Statements, Loops, break and continue. Output functions: write,writeln, popup boxes: prompt,
alert, confirm. Functions: Built-in Global Functions: alert(), prompt(),confirm(), isNan(), Number(),
parseInt(). User Defined Functions, Calling Functions with Timer,Events Familiarization: onLoad, onClick,
onBlur, onSubmit, onChange, Document Object Model(Concept). Objects: String, Array, Date.
JavaScript (js) is a light-weight object-oriented programming language which is used by several websites
for scripting the webpages. It is an interpreted, full-fledged programming language that enables dynamic
interactivity on websites when applied to an HTML document. It was introduced in the year 1995 for adding
programs to the webpages in the Netscape Navigator browser. Since then, it has been adopted by all other
graphical web browsers. With JavaScript, users can build modern web applications to interact directly
without reloading the page every time. The traditional website uses js to provide several forms of
interactivity and simplicity.
JavaScript was invented by Brendan Eich in 1995.
It was developed for Netscape 2, and became the ECMA-262 standard in 1997.
After Netscape handed JavaScript over to ECMA, the Mozilla foundation continued to develop
JavaScript for the Firefox browser. Mozilla's latest version was 1.8.5. (Identical to ES5).
Internet Explorer (IE4) was the first browser to support ECMA-262 Edition 1 (ES1).
ECMAScript 2023, the 14th and current version, was released in June 2023.
Features of JavaScript
1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a structured
programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the
operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than using classes
for inheritance.
Application of JavaScript
Client-side validation,
Dynamic drop-down menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and
prompt dialog box),
Displaying clocks etc.
HTML, CSS and JavaScript are used for Client- Node.js, PHP, Python and Java are used for Server-
side programming side programming
<script> Tag
The <script> tag is used to embed a client-side script (JavaScript).
The <script> element either contains scripting statements, or it points to an external script file
through the src attribute.
Common uses for JavaScript are image manipulation, form validation, and dynamic changes of
content.
Syntax of script tag
<script>
//code to be executed
</script>
3
</form>
</body>
</html>
JavaScript Variables
let num = 5;
In JavaScript, we use either var or let keyword to declare variables. For example,
var x;
let y;
var let
var is used in the older versions of let is the new way of declaring variables starting ES6
JavaScript (ES2015).
var is function let is block scoped
For example, var x; For example, let y;
Note: It is recommended we use let instead of var. However, there are a few browsers that do not support let.
JavaScript Initialize Variables
We use the assignment operator = to assign a value to a variable.
let x;
x = 5;
Here, 5 is assigned to variable x.
let x = 5;
let y = 6;
let x = 5, y = 6, z = 7;
5
JavaScript Constants
The const keyword was also introduced in the ES6(ES2015) version to create constants. For example,
const x = 5;
Once a constant is initialized, we cannot change its value.
6
const x = 5;
x = 10; // Error! constant cannot be changed.
console.log(x)
Simply, a constant is a type of variable whose value cannot be changed.
Also, you cannot declare a constant without initializing it. For example,
const x; // Error! Missing initializer in const declaration.
x = 5;
console.log(x)
JavaScript in HTML Document
JavaScript code is inserted between <script> and </script> tags when used in an HTML
document. Scripts can be placed inside the body or the head section of an HTML page or inside both the
head and body. We can also place JavaScript outside the HTML file which can be linked by specifying its
source in the script tag.
Add JavaScript Code inside Head Section
JavaScript code is placed inside the head section of an HTML page and the function is invoked when a
button is clicked.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Add JavaScript Code inside Head Section
</title>
<script>
function myFun() {
document.getElementById("demo")
.innerHTML = "Content changed!";
}
</script>
</head>
<body>
<h3 id="demo" style="color:green;">
Welcome to Javascript
</h3>
<button type="button" onclick="myFun()">
Click Here
</button>
7
</body>
</html>
Add JavaScript Code inside Body Section
JavaScript Code is placed inside the body section of an HTML page and the function is invoked when a
button is clicked.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript </title>
</head>
<body>
<h2>
Add JavaScript Code
inside Body Section
</h2>
<h3 id="demo" style="color:green;">
GeeksforGeeks
</h3>
<button type="button" onclick="myFun()">
Click Here
</button>
<script>
function myFun() {
document.getElementById("demo")
.innerHTML = "Content changed!";
}
</script>
</body>
</html>
External JavaScript
JavaScript can also be used in external files. The file extension of the JavaScript file will be .js. To use an
external script put the name of the script file in the src attribute of a script tag. External scripts cannot
contain script tags.
Example:
Script.js
External JavaScript
8
JavaScript can also be used in external files. The file extension of the JavaScript file will be .js. To use an
external script put the name of the script file in the src attribute of a script tag. External scripts cannot
contain script tags.
Example:
Script.js
function myFun () {
document.getElementById('demo')
.innerHTML = 'Paragraph Changed'
}
<!DOCTYPE html>
<html>
<head>
<title>
External JavaScript
</title>
</head>
<body>
<h3 id="demo" style="color:green;">
GeeksforGeeks
</h3>
<button type="button" onclick="myFun()">
Click Here
</button>
</body></html>
Advantages of External JavaScript
Cached JavaScript files can speed up page loading.
It makes JavaScript and HTML easier to read and maintain.
It separates the HTML and JavaScript code.
It focuses on code reusability which is one JavaScript Code that can run in various HTML files.
JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is
dynamically used by JavaScript engine. You need to use var here to specify the data type. It can hold any
type of values such as numbers, strings etc. For example:
var a=40;//holding number
var b="Rahul";//holding string
JavaScript Operators
JavaScript operators operate the operands, these are symbols that are used to manipulate a certain value or
operand. Operators are used to performing specific mathematical and logical computations on operands.
In other words, we can say that an operator operates the operands.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Arithmetic Operators
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No. Operator & Description
1 + (Addition)
10
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
<html>
<body>
<script type = "text/javascript">
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
11
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Comparison Operators
Assume variable A holds 10 and variable B holds 20, then −
= = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
1
becomes true.
Ex: (A == B) is not true.
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values are not
2
equal, then the condition becomes true.
Ex: (A != B) is true.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
document.write(result);
document.write(linebreak);
document.write("(a < b) => ");
result = (a < b);
document.write(result);
document.write(linebreak);
document.write("(a > b) => ");
result = (a > b);
document.write(result);
document.write(linebreak);
document.write("(a != b) => ");
result = (a != b);
document.write(result);
document.write(linebreak);
document.write("(a >= b) => ");
13
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...
Logical Operators
Assume variable A holds 10 and variable B holds 20, then −
|| (Logical OR)
2 If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical
3
NOT operator will make it false.
Ex: ! (A && B) is false.
14
Example
Try the following code to learn how to implement Logical Operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...
15
Bitwise Operators
Assume variable A holds 2 and variable B holds 3, then −
| (BitWise OR)
2 It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer
3 arguments. Exclusive OR means that either operand one is true or operand two
is true, but not both.
Ex: (A ^ B) is 1.
~ (Bitwise Not)
4 It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
16
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then try...
Assignment Operators
= (Simple Assignment )
1 Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.
Example
<html>
<body>
<script type = "text/javascript">
<!--
18
var a = 33;
var b = 10;
var linebreak = "<br />";
Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes one of the
two given statements depending upon the result of the evaluation.
? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be of any
type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string,
or booleanvalue and returns true or false based on the evaluation.
Here is a list of the return values for the typeof Operator.
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Example
<html>
<body>
<script type = "text/javascript">
var a = 10;
var b = "String";
var linebreak = "<br />";
Output
Result => B is String
Result => A is Numeric
{
console.log("Given number is even number.");
}
if (num % 2 !== 0)
{
console.log("Given number is odd number.");
}
JavaScript if-else Statement
The if-else statement will perform some action for a specific condition. Here we are using the else
statement in which the else statement is written after the if statement and it has no condition in their code
block.
if ( condition )
{
statement(s)
}
else
{
statements(s)
}
Example:
let age = 25;
if (age >= 18) {
document.write("You are eligible of driving licence")
} else {
document.write("You are not eligible for driving licence")
}
statements(s)
} else {
statements(s)
}
Example:
const num = 0;
if (num > 0) {
console.log("Given number is positive.");
} else if (num < 0) {
console.log("Given number is negative.");
} else {
console.log("Given number is zero.");
}
JavaScript Switch Statement
As the number of conditions increases, you can use multiple else-if statements in JavaScript. but when we
dealing with many conditions, the switch statement may be a more preferred option.
Syntax:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
default:
statementDefault;
}
const marks = 85;
let Branch;
switch (true) {
case marks >= 90:
Branch = "Computer science engineering";
break;
24
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It
makes the code compact. It is mostly used in array.
There are mainly two types of loops:
Entry Controlled Loop: In these types of loops, the test condition is tested before entering the loop
body. The for Loop and while Loop are entry-controlled loops.
Exit Controlled Loop: In these types of loops the test condition is tested or evaluated at the end of the
loop body. Therefore, the loop body will execute at least once, irrespective of whether the test
condition is true or false. The do-while loop is exit controlled loop.
1) JavaScript For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of
iteration is known.
Syntax
xfor (initialization; condition; increment/decrement)
{
code to be executed
}
25
Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already
declared variable can be used or a variable can be declared, local to loop only.
Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is
also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
Statement execution: Once the condition is evaluated to be true, the statements in the loop body are
executed.
Increment/ Decrement: It is used for updating the variable for the next iteration.
Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
JavaScript while loop
A while loop is a control flow statement that allows code to be executed repeatedly based on a given
Boolean condition.The syntax of while loop is given below.
while (condition)
{
code to be executed
}
The do-while loop is similar to the while loop with the only difference is that it checks for the condition
after executing the statements, and therefore is an example of an Exit Control Loop.But, code is executed
at least once whether condition is true or false.
The syntax of do while loop
do{
code to be executed
}while (condition);
The do-while loop starts with the execution of the
statement(s). There is no checking of any condition for the first time.
After the execution of the statements and update of the variable value, the condition is checked for a
true or false value. If it is evaluated to be true, the next iteration of the loop starts.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
It is important to note that the do-while loop will execute its statements at least once before any
condition is checked and therefore is an example of the exit control loop.
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Syntax
for (x in object) {
code block to be executed
}
Parameters
Parameter Description
x Required.
A variable to iterate over the properties.
object Required.
The object to be iterated
example
27
In JavaScript, popup boxes are used to display the message or notification to the user. JavaScript has three
kinds of popup boxes: Alert box, Confirm box, and Prompt box
Alert Box
It is used when a warning message is needed to be produced. When the alert box is displayed to the user,
the user needs to press ok and proceed.
Syntax
window.alert("sometext");
The window.alert() method can be written without the window prefix.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax:
window.confirm("sometext");
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
29
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after
entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax
window.prompt("SOME MESSAGE", "DEFAULT_VALUE");
Here, SOME MESSAGE is the message which is displayed in the popup box,
and DEFAULT_VALUE is the default value in the input field. The default value is an optional field.
The window.prompt() method can be written without the window prefix.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text;
let person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
text = "User cancelled the prompt.";
30
} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
Example
<html>
<body>
<script type="text/javascript">
var name=prompt("enter your name")
var result=confirm("do you want to save");
if(result)
{
alert("You have clicked ok button");
}
else
{
document.write("You have clicked cancel button");
}
</script>
</body>
</html>
<script>
Hello World!Have a nice day!
document.write("Hello World!");
</script>
31
WriteLine() method displays the output and also provides a new line character it the end of the string, This
would set a new line for the next output.
Syntax:
document.writeln( exp1, exp2, exp3, ... )
<script>
Hello World!
document.writeln("Hello World!"); Have a nice day!
</script>
JavaScript Output
There are certain situations in which you may need to generate output from your JavaScript code. For
example, you might want to see the value of variable, or write a message to browser console to help you
debug an issue in your running JavaScript code, and so on.
In JavaScript there are several different ways of generating output including
Writing into an HTML element, using innerHTML.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
Writing Output to Browser Console
You can easily outputs a message or writes data to the browser console
using the console.log() method.
For debugging purposes, you can call the console.log() method in the browser to
displaydata.
Eg
<!DOCTYPE html>
<html>
<head>
<title>Writing into the Browser's Console with JavaScript</title>
</head>
<body>
<script>
// Printing a simple text message
console.log("Hello World!"); // Prints: Hello World!
// Printing a variable
value var x = 10;
32
var y = 20;
var sum = x + y;
console.log(sum); // Prints: 30
</script>
<p><strong>Note:</strong> Please check out the browser console by pressing the
f12 key on the keyboard.</p>
</body>
</html>
Displaying Output in Alert Dialog Boxes
You can also use alert dialog boxes to display the message or output data to the user. An alert dialog
box is created using the window.alert() method.
example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Writing into an Alert Dialog Box with JavaScript</title>
</head>
<body>
<script>
// Displaying a simple text message alert("Hello World!"); // Outputs: Hello World!
// Displaying a variable
value var x = 10;
var y = 20;
var sum = x + y;
alert(sum); //
Outputs: 30
</script>
</body>
</html>
Example 2
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script> window.alert(5 + 6);
</script>
33
</body>
</html>
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
<button type="button" onclick="document.write('Hello World!')">Click Me</button>
</body>
</html>
Inserting Output Inside an HTML Element
You can also write or insert output inside an HTML element using the element's innerHTML
property. However, before writing the output first we need to select the element using a
method such as getElementById()
The id attribute defines the HTML element. The innerHTML property defines the HTML
content.
Changing the innerHTML property of an HTML element is a common way to display data in
HTML.,
Example:
<!DOCTYPE html>
<html>
<head>
<title>Writing into an HTML Element with JavaScript</title>
</head>
<body>
<p id="greet"></p>
<p id="result"></p>
<script>
// Writing text string inside an element
document.getElementById("greet").innerHTML = "Hello World!";
// Writing a variable value inside an element var x = 10;
var y = 20;
var sum = x + y; document.getElementById("result").innerHTML = sum;
</script>
</body>
</html>
Example2
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
35
<!DOCTYPE html>
<html>
<body>
</body>
</html>
isNaN()
In JavaScript NaN is short for "Not-a-Number".
The isNaN() method returns true if a value is NaN.
The isNaN() method converts the value to a number before testing it.
Syntax
isNaN(value)
Parameters
Parameter Description
value Required.
The value to be tested.
36
Return Value
Type Description
A boolean true if the value is NaN, otherwise false.
<p id="demo"></p>
<script>
Is 123 NaN? false
let result = Is -1.23 NaN? false
Is 5-2 NaN? false
"Is 123 NaN? " + isNaN(123) + "<br>" +
Is 0 NaN? false
"Is -1.23 NaN? " + isNaN(-1.23) + "<br>" +
Is 'Hello' NaN? true
"Is 5-2 NaN? " + isNaN(5-2) + "<br>" + Is '2005/12/12' NaN? true
document.getElementById("demo").innerHTML = result;
</script>
Number()
The Number() method converts a value to a number.
If the value cannot be converted, NaN is returned.
For booleans, Number() returns 0 or 1.
For dates, Number() returns milliseconds since January 1, 1970 00:00:00.
For strings, Number() returns a number or NaN.
Syntax
Number(value)
Parameters
Parameter Description
value Optional.
A JavaScript value (variable).
Return Value
Type Description
A number Returns the value as a number.
If the value cannot be converted to a number, NaN is returned.
If no value is provided, 0 is returned.
<p id="demo"></p>
Number() converts a value to a
number if possible:
1
0
37
<script>
document.getElementById("demo").innerHTML =
Number(true) + "<br>" +
Number(false) + "<br>" +
Number(new Date());
</script>
parseInt()
The parseInt method parses a value as a string and returns the first integer.
A radix parameter specifies the number system to use:
2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal.
If radix is omitted, JavaScript assumes radix 10. If the value begins with "0x", JavaScript assumes
radix 16.
Syntax
parseInt(string, radix)
Parameters
Parameter Description
value Required.
The value to be parsed.
radix Optional. Default is 10.
A number (2 to 36) specifying the number system.
Return Value
Type Description
A number. NaN if no integer is found.
<p id="demo"></p>
<script>
parseInt() parses a string and
document.getElementById("demo").innerHTML = returns the first integer:
parseInt("10") + "<br>" +
10
parseInt("10.00") + "<br>" +
10
parseInt("10.33") + "<br>" + 10
parseInt("34 45 66") + "<br>" + 34
60
parseInt(" 60 ") + "<br>" +
40
parseInt("40 years") + "<br>" + NaN
38
parseFloat()
The parseFloat() method parses a value as a string and returns the first number.
Syntax
parseFloat(value)
Parameters
Parameter Description
value Required.
The value to parse.
Return Value
Type Description
A number NaN if no number is found.
<p id="demo"></p> 10
<script> 10
document.getElementById("demo").innerHTML = 10.33
34
parseFloat(10) + "<br>" + NaN
parseFloat("10") + "<br>" +
parseFloat("10.33") + "<br>" +
parseFloat("34 45 66") + "<br>" +
parseFloat("He was 40");
</script>
String()
The String() method converts a value to a string.
Syntax
String(value)
Parameters
Parameter Description
value Required.
A JavaScript value.
Return Value
39
Type Description
A string. The value converted to a string.
<p id="demo"></p>
<script> Tue Oct 31 2023 23:47:25 GMT+0530
document.getElementById("demo").innerHTML =
(India Standard Time)
12345
String(new Date()) + "<br>" +
12345
String("12345") + "<br>" +
String(12345);
</script>
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code Automatically (self invoked)
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after
the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
40
<p id="demo"></p>
<script>
function myFunction(p1, p2) { 12
return p1 * p2;
}
let result = myFunction(4, 3);
document.getElementById("demo").innerHTML = result;
</script>
<p id="demo"></p>
<script>
let x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
JavaScript Timing Events
The window object allows execution of code at specified time intervals.
These time intervals are called timing events.
The two key methods to use with JavaScript are:
setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.
setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.
The setTimeout() Method
window.setTimeout(function, milliseconds);
The window.setTimeout() method can be written without the window prefix.
The first parameter is a function to be executed.
The second parameter indicates the number of milliseconds before execution.
Example
<body>
<h2>JavaScript Timing</h2>
<p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>
41
JavaScript Events
he change in the state of an object is known as an Event. In html, there are various events which represents
that some activity is performed by the user or by the browser. When javascript code is included in HTML, js
42
react over these events and allow the execution. This process of reacting over the events is called Event
Handling. Thus, js handles the HTML events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task to be performed
on the event.
Window/Document events
Click Event
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is JavaTpoint");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
MouseOver Event
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
44
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
Focus Event
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
//-->
</script>
</body>
Keydown Event
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
Load event
<body onload="window.alert('Page successfully loaded');">
<script>
45
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
onChange() event
<body>
<input onchange="alert(this.value)"
type="number"
style="margin-left: 45%;">
</body>
onSubmit() event
</form>
<script>
function myFunction() {
</script>
46
With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM is a standard object model and programming interface for HTML. It defines:
The HTML elements as objects
The properties of all HTML elements
The methods to access all HTML elements
The events for all HTML elements
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
JavaScript can change all the HTML elements in the page
JavaScript can change all the HTML attributes in the page
JavaScript can change all the CSS styles in the page
JavaScript can remove existing HTML elements and attributes
47
<body>
<h1>JavaScript Dates</h1>
<h2>Using new Date()</h2>
48
<p id="demo"></p>
<script>
const d = new Date("2022-03-25");
document.getElementById("demo").innerHTML = d;
</script>
</body>
JavaScript Date Methods
Methods Description
getDate() It returns the integer value between 1 and 31 that represents the day for the specified
date on the basis of local time.
getDay() It returns the integer value between 0 and 6 that represents the day of the week on the
basis of local time.
getFullYears() It returns the integer value that represents the year on the basis of local time.
getHours() It returns the integer value between 0 and 23 that represents the hours on the basis of
local time.
getMilliseconds() It returns the integer value between 0 and 999 that represents the milliseconds on the
basis of local time.
getMinutes() It returns the integer value between 0 and 59 that represents the minutes on the basis of
local time.
getMonth() It returns the integer value between 0 and 11 that represents the month on the basis of
local time.
getSeconds() It returns the integer value between 0 and 60 that represents the seconds on the basis of
local time.
getUTCDate() It returns the integer value between 1 and 31 that represents the day for the specified
date on the basis of universal time.
getUTCDay() It returns the integer value between 0 and 6 that represents the day of the week on the
basis of universal time.
getUTCFullYears() It returns the integer value that represents the year on the basis of universal time.
getUTCHours() It returns the integer value between 0 and 23 that represents the hours on the basis of
universal time.
getUTCMinutes() It returns the integer value between 0 and 59 that represents the minutes on the basis of
universal time.
getUTCMonth() It returns the integer value between 0 and 11 that represents the month on the basis of
49
universal time.
getUTCSeconds() It returns the integer value between 0 and 60 that represents the seconds on the basis of
universal time.
setDate() It sets the day value for the specified date on the basis of local time.
setDay() It sets the particular day of the week on the basis of local time.
setFullYears() It sets the year value for the specified date on the basis of local time.
setHours() It sets the hour value for the specified date on the basis of local time.
setMilliseconds() It sets the millisecond value for the specified date on the basis of local time.
setMinutes() It sets the minute value for the specified date on the basis of local time.
setMonth() It sets the month value for the specified date on the basis of local time.
setSeconds() It sets the second value for the specified date on the basis of local time.
toDateString() It returns the date portion of a Date object.
toString() It returns the date in the form of string.
valueOf() It returns the primitive value of a Date object.
JavaScript Current Time Example
Current Time: <span id="txt"></span>
<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>
JavaScript Array
An Array is a collection of data and a data structure that is stored in a sequence of memory locations.
One can access the elements of an array by calling the index number such as 0, 1, 2, 3, …, etc. The array
can store data types like Integer, Float, String, and Boolean all the primitive data types can be stored
in an array.There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
50
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't have to
provide value explicitly.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
51
Array Properties
The following table lists the standard properties of the Array object.
Property Description
length Sets or returns the number of elements in an array.
prototype Allows you to add new properties and methods to an Array object.
Array Methods
Method Description
concat() Merge two or more arrays, and returns a new array.
fill() Fill the elements in an array with a static value.
filter() Creates a new array with all elements that pass the test in a testing function.
find() Returns the value of the first element in an array that pass the test in a testing function.
findIndex() Returns the index of the first element in an array that pass the test in a testing function.
forEach() Calls a function once for each array element.
from() Creates an array from an object.
includes() Determines whether an array includes a certain element.
indexOf() Search the array for an element and returns its first index.
isArray() Determines whether the passed value is an array.
join() Joins all elements of an array into a string.
keys() Returns a Array Iteration Object, containing the keys of the original array.
lastIndexOf() Search the array for an element, starting at the end, and returns its last index.
map() Creates a new array with the results of calling a function for each array element.
pop() Removes the last element from an array, and returns that element.
push() Adds one or more elements to the end of an array, and returns the array's new length.
reverse() Reverses the order of the elements in an array.
shift() Removes the first element from an array, and returns that element.
slice() Selects a part of an array, and returns the new array.
some() Checks if any of the elements in an array passes the test in a testing function.
sort() Sorts the elements of an array.
splice() Adds/Removes elements from an array.
toString() Converts an array to a string, and returns the result.
unshift() Adds new elements to the beginning of an array, and returns the array's new length.
values() Returns a Array Iteration Object, containing the values of the original array.
52
Array length
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;
join()
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
Array pop()
Example
Array push()
The push() method adds a new element to an array (at the end):
Example
The concat() method creates a new array by merging (concatenating) existing arrays:
JavaScript String
JavaScript String Object is a sequence of characters. It contains zero or more characters within
single or double quotes.
In JavaScript, strings automatically convert the string to objects so that we can use string methods
and properties also for primitive strings
Syntax:
const string_name = "String Content"
or
const string_name = new String("String Content")
Example: In this example, we will create a string by using the native way and using String Constructor.
// Create a variable and assign String value
const str1 = "First String Content";
console.log("String 1: " + str1);
// Creating a String using String() Constructor
const str2 = String("Second String Content");
console.log("String 2: " + str2);