|

Java Script Class 12 Notes – Web Application (803)

JavaScript is one of the most important programming languages used in web development. It makes web pages interactive by allowing users to perform actions such as clicking buttons, entering data, displaying messages, validating forms, and responding to events.

In this Java Script Class 12 Notes, you will learn about functions, objects, strings, arrays, math methods, and event handling, which are essential concepts for building dynamic web applications and are frequently asked in CBSE examinations.

What is Functions

  • A function is one of the basic building blocks of JavaScript that contains a group of statements to perform a specific task or calculate a value.
  • A function works like a procedure, but it usually accepts input (parameters), processes the input, and returns an output (result).
  • The output produced by a function depends on the input provided, which shows a clear relationship between the input and the result.
  • Functions help in reusing code, as you can write the code once and use it many times whenever needed.
  • The same function can be called with different arguments (values), allowing it to produce different results without rewriting the code.
  • Using functions makes programs shorter, easier to understand, easier to maintain, and reduces code duplication.

Syntax

function functionName(parameter1, parameter2, parameter3) {
    // code to be executed
}

Example

<script>
    function addNumbers(a, b) {
        return a + b;
    }
</script>

Naming a Function

  • A function name should start with a letter and should clearly describe the task performed by the function.
  • Function names can contain letters, digits, underscores (_), and dollar signs ($), but they cannot contain spaces or other special characters.
  • JavaScript reserved keywords (such as if, for, function, etc.) cannot be used as function names.
  • Examples of valid function names are addNumbers() and changeCase().
  • Examples of invalid function names are 123Sum() (starts with a digit) and change Case() (contains a space).

Types of Functions in JavaScript

JavaScript functions are of two types:

  • Built-in Functions
  • User-defined Functions

Built-in Functions

  • Built-in functions are predefined functions that are already available in JavaScript.
  • Some commonly used built-in functions are:
    • prompt() – Takes input from the user as a string.
    • parseInt() – Converts a value into an integer.
    • parseFloat() – Converts a value into a floating-point (decimal) number.
    • isNaN() – Checks whether a value is Not a Number (NaN). It returns true if the value is not a number; otherwise, it returns false.
    • alert() – Displays a message in a pop-up dialog box.

User-Defined Functions

  • User-defined functions are functions created by the programmer to perform a specific task.
  • A user-defined function consists of:
    • A function name.
    • Parameters written inside parentheses ( ) (if required).
    • A block of code inside curly braces { }.
    • An optional return statement to return a result.
  • After defining a function, it must be called (invoked) to execute its code.

Syntax

    // code to be executed
    return some_result;
}
// Calling the function
func_name(arg1, arg2, arg3);

Example

<script>
    // Define the showUser function
    function showUser(username) {
        document.write(“User: ” + username);
    }
    // Call the function
    showUser(“Rahul Kumar”);
</script>

Output:

User: Rahul Kumar

Invoking (Calling) a Function

  • After a function is defined, it must be called (invoked) to execute the code written inside it.
  • A function is called by writing its name followed by parentheses ( ).
  • When a user-defined function is called, the program control is transferred to that function, and the statements inside the function are executed.
  • A function can be called immediately after its definition or anywhere in the program whenever it is needed.

Example

<script>
    // Function definition
    function greet() {
        document.write(“Hello, World!”);
    }
    // Function call
    greet();
</script>

Output:

Hello, World!


Using the return Keyword

  • The return keyword is used to send a value back to the place where the function was called.
  • As soon as JavaScript executes a return statement, the function stops executing and returns the specified value to the caller.
  • The returned value can be stored in a variable for later use.
  • The returned value can also be displayed directly by calling the function inside an output statement.
  • For example, a function can check whether a number is positive or negative and return the appropriate message. After the return statement is executed, the function ends and control goes back to the statement that called the function.

Example: Invoking a Function and Returning a Value

<html>
<head>
    <title>Functions</title>
</head>
<body>
<h3>Invoking a Function and Return Value</h3>
<script>
    // Define the JavaScript function
    function myJavaScriptFunction(num)
    {
        if (num < 0)
        {
            return “Number is negative”;
        }
        else
        {
            return “Number is positive”;
        }
    }
    // Invoke the function and store the returned value
    var result = myJavaScriptFunction(5);
    // Display the result
    document.write(result);
</script>
</body>
</html>

Output:

Invoking a Function and Return Value
Number is positive

Explanation

  • The function myJavaScriptFunction() accepts one parameter named num.
  • If the value of num is less than 0, the function returns “Number is negative”.
  • Otherwise, it returns “Number is positive”.
  • The function is called with the argument 5, so the else block is executed.
  • The returned value is stored in the variable result.
  • Finally, document.write(result) displays the output on the web page.

Note: Whenever a function uses the return statement, the returned value should either be stored in a variable or used directly in an output statement (such as document.write()). Otherwise, the returned value will not be displayed.

Invoking (Calling) a Function Multiple Times

  • A function can be called multiple times in the same program whenever its functionality is required.
  • Each time a function is called, different arguments (values) can be passed, allowing the same function to produce different results.
  • Reusing the same function avoids writing the same code repeatedly and makes the program shorter and easier to maintain.
  • If a function has two parameters, then two arguments should be passed while calling the function.
  • The first argument is assigned to the first parameter, and the second argument is assigned to the second parameter.
  • If a required argument is not passed, its corresponding parameter gets the value undefined. As a result, arithmetic operations involving that parameter usually produce NaN (Not a Number)`.

Example: Invoking (Calling) a Function Multiple Times

<html>
<head>
    <title>Functions</title>
</head>
<body>
<h3>Invoking a Function and Return Value</h3>
<script>
    function add(x, y)
    {
        var total = x + y;
        return total;
    }
    // Calling the function for the first time
    document.write(add(12, 13));
    document.write(“<br>”);
    // Calling the function for the second time
    document.write(add());
    document.write(“<br>”);
    // Calling the function for the third time
    document.write(add(2, 3, 4));
    document.write(“<br>”);
    // Calling the function for the fourth time
    var x = add(12.5, 13.5);
    document.write(x);
</script>
</body>
</html>

Output

25
NaN
5
26

Explanation

  • add(12, 13) returns 25 because 12 is assigned to x and 13 is assigned to y.
  • add() returns NaN because no arguments are passed, so both x and y become undefined. Adding undefined values results in NaN.
  • add(2, 3, 4) returns 5 because the function has only two parameters (x and y). Therefore, the third argument (4) is ignored.
  • add(12.5, 13.5) returns 26, which is stored in the variable x and then displayed using document.write(x).

Objects

  • Objects are one of the fundamental building blocks of JavaScript that are used to store and organize related data and functions together.
  • Objects help in storing and organizing data, creating reusable code, and developing complex and powerful applications.
  • An object consists of properties and methods.
    • Properties are characteristics of an object and store values.
    • Methods are functions associated with an object that perform specific tasks.
  • For example, consider an object named Car:
    • Properties: Colour = Yellow, Shape = Sports, Fuel = Electric
    • Methods: Start(), Accelerate(), Stop()
  • Objects can be created using the new keyword followed by the object name.
  • An object’s property can be accessed using dot notation (.).
    • Car.Colour
    • Car.Shape
  • The value of an object property can be changed using the assignment operator (=).
    • Car.Shape = “Sedan”;
  • An object property can be deleted using the delete keyword.
    • delete Car.Shape;
  • For example, if an object named person has properties such as name, age, and city, these properties can be accessed, modified, and deleted using dot notation.

Example: Creating and Accessing Object Properties

<script>
    // Defining a new object
    var person = {
        name: “Priya”,
        age: 30,
        city: “Mumbai”
    };
    // Access properties using dot notation
    document.write(person.name + “<br>”);
    // Output: Priya
    document.write(person.age + “<br>”);
    // Output: 30
</script>

Output:

Priya
30

Strings in JavaScript

  • A string is a data type used to store text in JavaScript.
  • In JavaScript, a string is also an object, so it has its own properties and methods.
  • A string can contain letters, numbers, special characters, and spaces.
  • Strings are written inside single quotes (‘ ‘) or double quotes (” “).
    • var name = “Rahul”;
    • var city = ‘Mumbai’;
  • Every character in a string has an index number that starts from 0.
  • A string can be accessed using both positive indexing (left to right) and negative indexing (right to left).

Example: “WORLD”

CharacterWORLD
Positive Index01234
Negative Index-5-4-3-2-1

String Property

  • A property provides information about a string.
  • In your syllabus, the only string property is length.
  • The length property returns the total number of characters in a string, including spaces.
  • To find the length of a string, use the built-in length property.
  • var str = “Hello”;
  • document.write(str.length);   // Output: 5

Example 1: Finding the Length of a String

<script>
    var str = “Hello World”;
    var len = str.length;
    alert(“Length of the string ‘Hello World’: ” + len);
</script>

Output:

Length of the string ‘Hello World’: 11


Example 2: Using the length Property with a for Loop

The following example uses the length property to display each character of a string one by one.

<script>
    var str = “Hello World”;
    var len = str.length;
    for (i = 0; i < len; i++)
    {
        document.write(str[i] + “<br>”);
    }
</script>

Output:

H
e
l
l
o
W
o
r
l
d

String Methods

String methods are built-in functions that perform different operations on strings, such as extracting, replacing, converting, joining, or searching text.

MethodDescriptionExampleOutput
slice(start, end)Extracts a part of a string and returns it as a new string. The end index is not included. It also supports negative indexing.text.slice(6, 10)Worl
text.slice(-5, -2)Wor
If only the start index is given, it extracts the string from that index to the end.text.slice(6)World
substring(start, end)Extracts a part of a string without changing the original string. The end index is not included. It does not support negative indexing.text.substring(6, 9)Wor
If only the start index is given, it extracts the string from that index to the end.text.substring(6)World
replace(old, new)Replaces the first occurrence of the specified text with a new text.text.replace(“o”, “a”)Hella World
replaceAll(old, new)Replaces all occurrences of the specified text with new text.text.replaceAll(“l”, “r”)Herro Worrd
match(text)Checks whether the specified text matches the string. If found, it returns the matched text; otherwise, it returns null.text.match(“World”)World
text.match(“world”)null
toUpperCase()Converts all characters in the string to uppercase.text.toUpperCase()HELLO WORLD
toLowerCase()Converts all characters in the string to lowercase.text.toLowerCase()hello world
concat(str)Joins one or more strings to the end of the original string.text.concat(” Java”)Hello World Java
text.concat(” to “, “Java”, “Script”)Hello World to JavaScript
trim()Removes extra spaces from the beginning and end of a string.text.trim()Hello World
charAt(index)Returns the character present at the specified index.text.charAt(6)W

Note: In the above examples, assume:

var text = “Hello World”;

Example: String Methods in JavaScript

<script>
    var str = “Hello World”;
    // slice(): Extracts a part of a string and returns it as a new string
    var sliced = str.slice(2, 7);
    document.write(“slice(): ” + sliced + “<br>”);
    // Output: slice(): llo W
    // substring(): Returns the characters between two indexes
    var substrLast = str.substring(2, 7);
    document.write(“substring(): ” + substrLast + “<br>”);
    // Output: substring(): llo W
    // replace(): Replaces the first occurrence of a string
    var replaced = str.replace(“World”, “Universe”);
    document.write(“replace(): ” + replaced + “<br>”);
    // Output: replace(): Hello Universe
    // replaceAll(): Replaces all occurrences of a string
    var replacedAll = str.replaceAll(“o”, “0”);
    document.write(“replaceAll(): ” + replacedAll + “<br>”);
    // Output: replaceAll(): Hell0 W0rld
    // match(): Searches for a string and returns the matched text, otherwise null
    var text = “He shook the book”;
    document.write(text.match(“ook”) + “<br>”);
    document.write(text.match(“xyz”) + “<br>”);
    // Output:
    // ook
    // null
    // toUpperCase(): Converts the string to uppercase
    var upperCase = str.toUpperCase();
    document.write(“toUpperCase(): ” + upperCase + “<br>”);
    // Output: toUpperCase(): HELLO WORLD
    // toLowerCase(): Converts the string to lowercase
    var lowerCase = str.toLowerCase();
    document.write(“toLowerCase(): ” + lowerCase + “<br>”);
    // Output: toLowerCase(): hello world
    // concat(): Joins two or more strings
    var concatenated = str.concat(“, how are you?”);
    document.write(“concat(): ” + concatenated + “<br>”);
    // Output: concat(): Hello World, how are you?
    // charAt(): Returns the character at the specified index
    var char = str.charAt(6);
    document.write(“charAt(): ” + char + “<br>”);
    // Output: charAt(): W
</script>

Output

slice(): llo W
substring(): llo W
replace(): Hello Universe
replaceAll(): Hell0 W0rld
ook
null
toUpperCase(): HELLO WORLD
toLowerCase(): hello world
concat(): Hello World, how are you?
charAt(): W

Arrays in JavaScript

  • An array is a data structure used to store multiple values in a single variable.
  • Arrays act like a container that can hold several related items together.
  • An array can store different types of data such as numbers, strings, objects, and even other arrays.
  • JavaScript arrays are zero-indexed, which means:
    • The first element is stored at index 0.
    • The second element is stored at index 1, and so on.

Creating an Array

There are two ways to create an array in JavaScript.

Creating an Array using Array Literal

  • This is the most common and simplest way to create an array.
  • The elements are written inside square brackets [ ] and separated by commas.

Example

<script>
    // Using array literal
    var arrLiteral = [1, 2, 3, 4, 5];
    document.write(“Array created with array literal: ” + arrLiteral);
</script>

Output

Array created with array literal: 1,2,3,4,5


Creating an Array using the new Keyword

  • An array can also be created using the new Array() constructor.

Example

<script>
    // Creating an array using the new keyword
    var arrInstance = new Array(1, 2, 3, 4, 5);
    document.write(“Array created with instance of Array: ” + arrInstance);
</script>

Output

Array created with instance of Array: 1,2,3,4,5


Accessing Elements of an Array

  • Array elements are accessed using their index number.
  • Since indexing starts from 0, the first element is accessed using index 0.
  • The last element of an array can be accessed using:
    arrayName[arrayName.length – 1]

Modifying Array Elements

An element in an array can be changed by assigning a new value to its index.
arrayName[index] = newValue;

Array Length

The length property returns the total number of elements present in an array.
arrayName.length


Example: Accessing, Modifying, and Finding the Length of an Array

<script>
    // Creating an array
    var myArray = [10, 20, 30, 40, 50];
    // Accessing the first element
    var firstElement = myArray[0];
    document.write(“First Element: ” + firstElement + “<br>”);
    // Output: First Element: 10
    // Accessing the last element
    var lastElement = myArray[myArray.length – 1];
    document.write(“Last Element: ” + lastElement + “<br>”);
    // Output: Last Element: 50
    // Modifying the third element
    myArray[2] = 35;
    document.write(“Modified Array: ” + myArray + “<br>”);
    // Output: Modified Array: 10,20,35,40,50
    // Finding the length of the array
    var arrayLength = myArray.length;
    document.write(“Array Length: ” + arrayLength);
    // Output: Array Length: 5
</script>

Output

First Element: 10
Last Element: 50
Modified Array: 10,20,35,40,50
Array Length: 5

Array Methods

Array methods are built-in functions used to perform different operations on arrays, such as adding, removing, joining, sorting, and extracting elements.

Assume the following array is used in all examples:
var colors = [‘Red’, ‘Green’, ‘Blue’, ‘Yellow’];

MethodDescriptionExampleOutput
toString()Converts all array elements into a string separated by commas.colors.toString()Red,Green,Blue,Yellow
pop()Removes the last element from the array and returns it.colors.pop()Red, Green, Blue
push(item)Adds a new element at the end of the array.colors.push(“Purple”)Red, Green, Blue, Yellow, Purple
shift()Removes the first element from the array and shifts the remaining elements to lower indexes.colors.shift()Green, Blue, Yellow
unshift(item)Adds a new element at the beginning of the array and shifts the remaining elements to higher indexes.colors.unshift(“Orange”)Orange, Red, Green, Blue, Yellow
join(separator)Joins all array elements into a single string using the specified separator.colors.join(“&”)Red&Green&Blue&Yellow
concat(array)Combines two or more arrays into a new array.colors.concat([‘Cyan’, ‘Magenta’])Red, Green, Blue, Yellow, Cyan, Magenta
slice(start, end)Returns a new array containing selected elements. The end index is not included.colors.slice(1, 3)Green, Blue
reverse()Reverses the order of elements in the original array.colors.reverse()Yellow, Blue, Green, Red
sort()Sorts string elements in ascending alphabetical order.colors.sort()Blue, Green, Red, Yellow
deleteRemoves an element from a specific index but does not change the array length. The deleted position becomes empty.delete colors[1]Red, , Blue, Yellow

Example: Array Methods in JavaScript

<script>
    // Creating an array
    var fruits = [‘Apple’, ‘Banana’, ‘Cherry’];
    // Using toString() method
    document.write(“Using toString(): ” + fruits.toString() + “<br>”);
    // Output: Apple,Banana,Cherry
    // Using pop() method
    var popped = fruits.pop();
    document.write(“Using pop(): ” + fruits + “<br>”);
    document.write(“Popped element: ” + popped + “<br>”);
    // Output:
    // Using pop(): Apple,Banana
    // Popped element: Cherry
    // Using push() method
    fruits.push(“Date”);
    document.write(“Using push(): ” + fruits + “<br>”);
    // Output: Apple,Banana,Date
    // Using shift() method
    var shifted = fruits.shift();
    document.write(“Using shift(): ” + fruits + “<br>”);
    document.write(“Shifted element: ” + shifted + “<br>”);
    // Output:
    // Using shift(): Banana,Date
    // Shifted element: Apple
    // Using unshift() method
    fruits.unshift(“Apricot”);
    document.write(“Using unshift(): ” + fruits + “<br>”);
    // Output: Apricot,Banana,Date
    // Using join() method
    document.write(“Using join(): ” + fruits.join(“-“) + “<br>”);
    // Output: Apricot-Banana-Date
    // Using delete operator
    delete fruits[1];
    document.write(“Using delete(): ” + fruits + “<br>”);
    // Output: Apricot,,Date
    // Using concat() method
    var moreFruits = [‘Fig’, ‘Grapes’];
    var allFruits = fruits.concat(moreFruits);
    document.write(“Using concat(): ” + allFruits + “<br>”);
    // Output: Apricot,,Date,Fig,Grapes
    // Using slice() method
    var slicedFruits = allFruits.slice(1, 4);
    document.write(“Using slice(): ” + slicedFruits + “<br>”);
    // Output: ,Date,Fig
    // Using sort() method
    var sortedFruits = allFruits.sort();
    document.write(“Sorted array: ” + sortedFruits + “<br>”);
    // Output: ,Apricot,Date,Fig,Grapes
    // Using reverse() method
    var reversedFruits = sortedFruits.reverse();
    document.write(“Reversed array: ” + reversedFruits + “<br>”);
    // Output: Grapes,Fig,Date,Apricot,
</script>

Output

Using toString(): Apple,Banana,Cherry
Using pop(): Apple,Banana
Popped element: Cherry
Using push(): Apple,Banana,Date
Using shift(): Banana,Date
Shifted element: Apple
Using unshift(): Apricot,Banana,Date
Using join(): Apricot-Banana-Date
Using delete(): Apricot,,Date
Using concat(): Apricot,,Date,Fig,Grapes
Using slice(): ,Date,Fig
Sorted array: ,Apricot,Date,Fig,Grapes
Reversed array: Grapes,Fig,Date,Apricot,

Note: The delete operator removes the value at the specified index but does not remove the empty position from the array. Therefore, the array length remains unchanged.

Example: pop() Method

The pop() method removes the last element from an array and returns the removed element.

<!DOCTYPE html>
<html>
<body>
<h2>The pop() Method</h2>
<p>This method removes the last element from an array.</p>
<p>The return value of the <code>pop()</code> method is the removed item.</p>
<p id=”demo1″></p>
<p id=”demo2″></p>
<p id=”demo3″></p>
<script>
    var Students = [“Anmol”, “Bijoy”, “Inara”, “Vaibhavi”];
    // Display the original array
    document.getElementById(“demo1”).innerHTML = Students;
    // Remove and display the last element
    document.getElementById(“demo2”).innerHTML = Students.pop();
    // Display the array after removing the last element
    document.getElementById(“demo3”).innerHTML = Students;
</script>
</body>
</html>

Output
Anmol,Bijoy,Inara,Vaibhavi
Vaibhavi
Anmol,Bijoy,Inara

Explanation

  • The original array contains [“Anmol”, “Bijoy”, “Inara”, “Vaibhavi”].
  • The pop() method removes the last element (Vaibhavi) from the array.
  • The removed element is displayed in demo2.
  • After removing the last element, the remaining array [“Anmol”, “Bijoy”, “Inara”] is displayed in demo3.

Example: push() Method

The push() method adds a new element at the end of an array. It returns the new length of the array after the element is added.

<!DOCTYPE html>
<html>
<body>
<h2>The push() Method</h2>
<p>This method appends a new element to an array.</p>
<p>The return value of the <code>push()</code> method is the number of items in the array.</p>
<p id=”demo1″></p>
<p id=”demo2″></p>
<p id=”demo3″></p>
<script>
    var Students = [“Anmol”, “Bijoy”, “Inara”, “Vaibhavi”];
    // Display the original array
    document.getElementById(“demo1”).innerHTML = Students;
    // Add a new element and display the new array length
    document.getElementById(“demo2”).innerHTML = Students.push(“Nitasha”);
    // Display the updated array
    document.getElementById(“demo3”).innerHTML = Students;
</script>
</body>
</html>

Output

Anmol,Bijoy,Inara,Vaibhavi
5
Anmol,Bijoy,Inara,Vaibhavi,Nitasha

Explanation

  • The original array contains 4 elements.
  • The push() method adds “Nitasha” to the end of the array.
  • It returns 5, which is the new number of elements in the array.
  • The updated array becomes [“Anmol”, “Bijoy”, “Inara”, “Vaibhavi”, “Nitasha”].

Example: shift() Method

The shift() method removes the first element from an array, shifts the remaining elements one position to the left, and returns the removed element.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript shift() Method</h2>
<p>The <code>shift()</code> method removes the first element of an array and shifts the remaining elements to the left.</p>
<p id=”demo1″></p>
<p id=”demo2″></p>
<p id=”demo3″></p>
<script>
    var Students = [“Anmol”, “Bijoy”, “Inara”, “Vaibhavi”];
    // Display the original array
    document.getElementById(“demo1”).innerHTML = Students;
    // Remove and display the first element
    document.getElementById(“demo2”).innerHTML = Students.shift();
    // Display the updated array
    document.getElementById(“demo3”).innerHTML = Students;
</script>
</body>
</html>

Output

Anmol,Bijoy,Inara,Vaibhavi
Anmol
Bijoy,Inara,Vaibhavi

Explanation

  • The original array contains [“Anmol”, “Bijoy”, “Inara”, “Vaibhavi”].
  • The shift() method removes the first element (Anmol).
  • The removed element is displayed.
  • The remaining elements shift one position to the left, resulting in [“Bijoy”, “Inara”, “Vaibhavi”].

Example: unshift() Method

The unshift() method adds one or more elements at the beginning of an array and returns the new length of the array.

<!DOCTYPE html>
<html>
<body>
<h2>The unshift() Method</h2>
<p>The <code>unshift()</code> method adds new elements to the beginning of an array.</p>
<p id=”demo1″></p>
<p id=”demo2″></p>
<p id=”demo3″></p>
<script>
    var Students = [“Anmol”, “Bijoy”, “Inara”, “Vaibhavi”];
    // Display the original array
    document.getElementById(“demo1”).innerHTML = Students;
    // Add a new element at the beginning and display the new array length
    document.getElementById(“demo2”).innerHTML = Students.unshift(“Jai”);
    // Display the updated array
    document.getElementById(“demo3”).innerHTML = Students;
</script>
</body>
</html>

Output

Anmol,Bijoy,Inara,Vaibhavi
5
Jai,Anmol,Bijoy,Inara,Vaibhavi

Explanation

  • The original array contains 4 elements.
  • The unshift() method adds “Jai” at the beginning of the array.
  • It returns 5, which is the new number of elements in the array.
  • The updated array becomes [“Jai”, “Anmol”, “Bijoy”, “Inara”, “Vaibhavi”].

Example: sort() Method

The sort() method sorts the elements of an array. By default, it sorts strings in alphabetical order and numbers as strings, which may produce unexpected results for numeric arrays.

<!DOCTYPE html>
<html>
<body>
<p>Click the button to sort the elements of the array.</p>
<button onclick=”sort_arr()”>Sort Array</button>
<p id=”demo1″></p>
<p id=”demo2″></p>
<script>
    var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
    var num = [20, 2, 1, 100, 110, 30, 4];
    function sort_arr()
    {
        // Sort string array
        fruits.sort();
        document.getElementById(“demo1”).innerHTML = fruits;
        // Sort numeric array (sorted as strings)
        num.sort();
        document.getElementById(“demo2”).innerHTML = num;
    }
</script>
</body>
</html>

Output (After Clicking the Button)

Apple,Banana,Mango,Orange
1,100,110,2,20,30,4

Explanation

  • The sort() method arranges string arrays in alphabetical order.
  • For numeric arrays, the default sort() method compares numbers as strings, not as numeric values.
  • Therefore, the numeric array is sorted as:
    1,100,110,2,20,30,4
    instead of:
    1,2,4,20,30,100,110

Example: reverse() Method

The reverse() method reverses the order of the elements in an array. It changes the original array.

<body>
<!DOCTYPE html>
<html>
<p>Click the button to reverse the order of the elements in the array.</p>
<button onclick=”rev_arr()”>Reverse Array</button>
<p id=”demo1″></p>
<script>
    var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
    function rev_arr()
    {
        fruits.reverse();
        document.getElementById(“demo1”).innerHTML = fruits;
    }
</script>
</body>
</html>

Output (After Clicking the Button)

Mango,Apple,Orange,Banana

Explanation

  • The reverse() method changes the order of the elements.
  • The first element becomes the last, and the last element becomes the first.
  • The original array is modified.

Example: Reverse Sorting an Array

To sort an array in descending order, first use sort() and then reverse().

<!DOCTYPE html>
<html>
<body>
<p>Click the button to sort the array in reverse order.</p>
<button onclick=”sort_arr()”>Reverse Sort Array</button>
<p id=”demo1″></p>
<p id=”demo2″></p>
<script>
    var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
    var num = [20, 2, 1, 100, 110, 30, 4];
    function sort_arr()
    {
        // Reverse alphabetical order
        fruits.sort();
        fruits.reverse();
        document.getElementById(“demo1”).innerHTML = fruits;
        // Reverse order for numeric array
        num.sort();
        num.reverse();
        document.getElementById(“demo2”).innerHTML = num;
    }
</script>
</body>
</html>

Output (After Clicking the Button)

Orange,Mango,Banana,Apple
4,30,20,2,110,100,1

Explanation

  • The string array is first sorted alphabetically and then reversed to produce reverse alphabetical order.
  • The numeric array is also sorted as strings and then reversed. Therefore, the output is not true descending numeric order.

Note: In JavaScript, the default sort() method sorts numbers as strings. To sort numbers correctly in ascending or descending order, a compare function is required, which is beyond the scope of this syllabus.

Math Methods

The Math object in JavaScript provides built-in methods to perform mathematical calculations. You can use these methods directly with the Math object without creating a Math object.

MethodDescriptionExampleOutput
Math.round(x)Rounds a number to the nearest integer.Math.round(5.5)6
Math.round(5.49)5
Math.ceil(x)Returns the smallest integer greater than or equal to the given number.Math.ceil(5.1)6
Math.ceil(5.9)6
Math.floor(x)Returns the largest integer less than or equal to the given number.Math.floor(5.1)5
Math.floor(5.9)5
Math.pow(x, y)Returns the value of x raised to the power y.Math.pow(2, 3)8
Math.sqrt(x)Returns the square root of a number.Math.sqrt(16)4
Math.min()Returns the smallest value from the given numbers.Math.min(5, -2, 8, 1, 2)-2
Math.max()Returns the largest value from the given numbers.Math.max(5, -2, 8, 1, 2)8
Math.random()Returns a random decimal number between 0 (inclusive) and 1 (exclusive).Math.random()Random number between 0 and 1

Note: The Math object is built into JavaScript, so you can directly use methods such as Math.round(), Math.sqrt(), and Math.random() without creating an object.

Example: Math Methods in JavaScript

<div id=”output”></div>
<script>
    var z = document.getElementById(“output”);
    // Math.round(x): Returns the value of a number rounded to the nearest integer
    z.innerHTML = “Math.round(4.4): ” + Math.round(4.4) + “<br>”;
    z.innerHTML += “Math.round(4.6): ” + Math.round(4.6) + “<br><br>”;
    // Math.ceil(x): Returns the integer greater than or equal to a given number
    z.innerHTML += “Math.ceil(4.1): ” + Math.ceil(4.1) + “<br>”;
    z.innerHTML += “Math.ceil(4.9): ” + Math.ceil(4.9) + “<br><br>”;
    // Math.floor(x): Returns the integer less than or equal to a given number
    z.innerHTML += “Math.floor(4.1): ” + Math.floor(4.1) + “<br>”;
    z.innerHTML += “Math.floor(4.9): ” + Math.floor(4.9) + “<br><br>”;
    // Math.pow(x, y): Returns x raised to the power y
    z.innerHTML += “Math.pow(3, 4): ” + Math.pow(3, 4) + “<br><br>”;
    // Math.sqrt(x): Returns the square root of a number
    z.innerHTML += “Math.sqrt(25): ” + Math.sqrt(25) + “<br><br>”;
    // Math.min(): Returns the smallest of zero or more numbers
    z.innerHTML += “Math.min(3, 7, 2, 9, 1): ” + Math.min(3, 7, 2, 9, 1) + “<br><br>”;
    // Math.max(): Returns the largest of zero or more numbers
    z.innerHTML += “Math.max(3, 7, 2, 9, 1): ” + Math.max(3, 7, 2, 9, 1) + “<br><br>”;
    // Math.random(): Returns a pseudo-random number between 0 and 1
    z.innerHTML += “Math.random(): ” + Math.random();
</script>

Output:

Math.round(4.4): 4
Math.round(4.6): 5
Math.ceil(4.1): 5
Math.ceil(4.9): 5
Math.floor(4.1): 4
Math.floor(4.9): 4
Math.pow(3, 4): 81
Math.sqrt(25): 5
Math.min(3, 7, 2, 9, 1): 1
Math.max(3, 7, 2, 9, 1): 9
Math.random(): 0.573291846

Note: The value returned by Math.random() is different every time the program runs because it generates a random decimal number between 0 (inclusive) and 1 (exclusive).

Events in JavaScript

  • An event is an action or occurrence that takes place in a web page, such as clicking a button, pressing a key, or loading a page.
  • Event handling is the process of responding to an event by executing a JavaScript function.
  • JavaScript provides event handlers, which are functions that are automatically called whenever a specific event occurs.
  • For example:
    • The onclick event is triggered when the user clicks on an element.
    • The onload event is triggered when the web page finishes loading.

Common JavaScript Events

EventEvent HandlerDescription
ChangeonchangeOccurs when the value of a form element is changed.
ClickonclickOccurs when the user clicks on an element.
Mouse OveronmouseoverOccurs when the mouse pointer moves over an element.
Mouse OutonmouseoutOccurs when the mouse pointer leaves an element.
Key DownonkeydownOccurs when the user presses a key on the keyboard.
LoadonloadOccurs after the browser finishes loading the web page.

Example: JavaScript Events

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Events</title>
</head>
<body onload=”onPageLoad()”>
    <h1>JavaScript HTML Events</h1>
    <h2>The onclick Event</h2>
    <button onclick=”showTime()”>The time is?</button>
    <p id=”demo”></p>
    <h2>The onchange Event</h2>
    <input type=”text” id=”myInput” onchange=”handleChange()”
           placeholder=”Type something…”>
    <h2>The onmouseover Event</h2>
    <div id=”mouseOverDiv” onmouseover=”mouseOverFunction()”>
        Mouse over me!
    </div>
    <h2>The onmouseout Event</h2>
    <div id=”mouseOutDiv” onmouseout=”mouseOutFunction()”>
        Mouse out of me!
    </div>
    <h2>The onkeydown Event</h2>
    <input type=”text” id=”myKeyDownInput”
           onkeydown=”keyDownFunction()”
           placeholder=”Press any key…”>
    <script>
        function onPageLoad()
        {
            alert(“Page loaded!”);
        }
        function showTime()
        {
            document.getElementById(“demo”).innerHTML = Date();
        }
        function handleChange()
        {
            alert(“The input value has changed.”);
        }
        function mouseOverFunction()
        {
            alert(“Mouse is over the element.”);
        }
        function mouseOutFunction()
        {
            alert(“Mouse left the element.”);
        }
        function keyDownFunction()
        {
            alert(“A key was pressed.”);
        }
    </script>
</body>
</html>

Output

  • When the web page loads, an alert box displays:
    Page loaded!
  • Clicking OK on the alert box loads the web page.
  • Clicking the “The time is?” button displays the current date and time.
  • Changing the text in the input box triggers the onchange event.
  • Moving the mouse over the “Mouse over me!” text triggers the onmouseover event.
  • Moving the mouse away from the “Mouse out of me!” text triggers the onmouseout event.
  • Pressing any key inside the last text box triggers the onkeydown event.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *