JavaScript Class 12 Notes

JavaScript is one of the most important topics in the Class 12 Web Application curriculum. It is a powerful scripting language used to create dynamic and interactive web pages. In these JavaScript Class 12 notes, you will learn about variables, data types, operators, functions, loops, objects, events.

Contents show

JavaScript Class 12 Notes

JavaScript was developed in 1995 by Brendan Eich, a computer scientist and programmer at Netscape Communications Corporation. JavaScript use interpreted language to execute the code. Interpreter execute the code line by line and if any error found then it will stop in that particular line. JavaScript can be implemented using tags.

There are three different places in the HTML document where scripts can be used.

  • Body of the page
  • Header of the page
  • Using external file

Advantages of JavaScript

  1. It is relatively easy to learn and use.
  2. It can be used for client-side and server-side i.e. front end and back end.
  3. It provides dynamism and interactivity on websites.
  4. It runs on multiple platforms and devices. It is supported by all browsers.
  5. There are many libraries, frameworks, and APIs available to facilitate tasks
  6. It can create visually appealing web projects and to create drag & drop components like sliders etc. to make the website more professional.

Data Types

Data type in Javascrip is used to store the value. JavaScript supports different type of data types. JavaScript includes Primitive and Non-Primitive data types. The primitive data types in JavaScript include string, number, Boolean, undefined & null. The non-primitive data type includes the object, array and functions.

Primitive Data Types

1. Numbers

A number data type can be an integer, a floating-point value, an exponential value, a ‘NaN’ or ‘Infinity’.

  • Integer value: Integer value are whole numbers like 67, 33, 5, 99 etc.
  • Floating-point value: There are numbers which have a decimal points like 67.4, 5.4, 55,0 etc.
  • Exponential value: Exponential value are represent very large or very small number using scientific notation like 10*10000;
  • NaN: In JavaScript NaN stands for “Not-a-Number; A ‘NaN’ is used when we want to check weather the data is numerical value or nor-numerical.
  • Infinity: If a number is divided by 0, the resulting value is infinity.
var integer = 42; // Integer value
var float = 3.14; // Floating-point value
var exponential = 2e3; // Exponential value: 2 × 1000 = 2000 (means means 2 × 103)
var notANumber = "abc" / 2; // NaN: Invalid math operation
var infinity = 10 / 0; // Infinity: Division by zero

console.log("Integer:", integer);
console.log("Floating-point:", float);
console.log("Exponential:", exponential);
console.log("NaN (Not-a-Number):", notANumber);
console.log("Infinity:", infinity);
2. String:

The string data type in JavaScript can be any group of characters enclosed by a single or double-quotes. To place a pair of quotes within a string, the two should be different.

  1. var str1 = “This is a string1 “; // This is a string primitive type or string literal
  2. var str2= ‘This is a string2 ‘;
  3. var str3 = ‘This is a ” string3 ” within another string ‘;
3. Boolean:

The Boolean data type has only two values, true and false. It is mostly used to check a logical condition. Thus Booleans are logical data types which can be used for comparison of two variables or to check a condition. The true and false imply a ‘yes’
for ‘true’ and a ‘no’ for ‘false’.

Let’s see an example of comparison statement where the output is a Boolean:

var a =5;
var b=6;
a==b // This will return false
4. Undefined:

Undefined data type means a variable that is not defined. The variable is declared but doesn’t contain any value.

var a;
document.write(a) // This will return undefined.
5. Null

The Null in JavaScript is a data type that is represented by only one value, the ‘null’ itself. A null value means no value.

var a = null;
document.write(a) // This gives output null
typeof(a) //This will return object

Non-Primitive Data Types

These types of data type are complex in nature which consist of more than one component. Objects, arrays and functions are examples of composite data types.

Variables

Variables are like a contener which is used to store value. You can place data into these containers and then refer to the data simply by naming the container. JavaScript variables must have unique names. These names are called Identifiers.

Variable Declaration and Initialization

  1. Variables in JavaScript can be defined using the keyword var (in the newer versions of JavaScript the keyword let is also used).
  2. The equal to (=) sign is used to assign a value to a variable.
  3. Users can either, separately declare the variable and then assign values to it or straight-away declare and initialize the variables.
  4. JavaScript variables can store a value of any data type. For example, you can store a number, string, Boolean, object, etc. data type values in JavaScript variables.
  5. The value and data type of a variable can change during the execution of a program and JavaScript takes care of it automatically

JavaScript Variable Scope

  • Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
  • Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

JavaScript Literals

JavaScript Literals are the values that are assigned to a variable , When you assign a literal to a variable. It automatically sets the data type. So a JavaScript Literal can be a numeric, string, floating-point value, an array , Boolean value or even an object.

1. Operators

In JavaScript, an operator is a symbol that performs an operation on one or more operands, such as variables or values, and returns a result.

Arithmetic Operators

Assume variable a has value 10 and variable b has value 20 then:

Arithmetic Operators in javascript
Comparison Operators

Assume variable a has value 10 and variable b has value 20 then:

Comparison Operators in javascript
Logical Operators

Assume variable a has value 10 and variable b has value 20 then:

Logical Operators javascript 1
Assignment Operators
Assignment Operators in javascript

Conditional operator (? 🙂

The conditional operator is also called the ternary operator, containing the 3 parts. The first part contains the condition and executes the second part if the condition evaluates the true; Otherwise, it executes the third part.

Conditional operator in javascript

Parameters

  • Condition − It is a conditional statement.
  • First Statement − If the conditional statement evaluates true, First Statement will be executed.
  • Second Statement − If the conditional statement evaluates false, the Second statement will be executed.

typeof operator

typeof in JavaScript is an operator that checks and returns the data type of the operand passed to it, the operand can be any array, string, number etc. whose type you want to find out.

var x=5;
document.write(typeof(x));

1. Functions

A function is like a small method which can take input, process the inputs and give back a result. It is a fundamental building block. They are useful because you can define the code once and use it many times. It is also useful to break complex problems into smaller parts.

Syntax of function:

function functionName(parameter1, parameter2) {
// Code to execute
return result;
}

A simple function for finding the sum of two numbers:

function addNumbers(a, b) {
return a + b;
}

let sum = addNumbers(5, 3);
  • ‘function’ is the keyword.
  • addNumbers is the function name.
  • (a, b) are parameters.
  • { return a + b; } is the function body.

Creating a Function

  • The function keyword and the function’s name come first in a function declaration. In function names, the same characters that are used for variables may also be used: underscores, dollar signs, digits, and letters.
  • A list of the arguments for the function, enclosed in parentheses and separated by commas.
  • Curly brackets { } surround the code that needs to be executed for the function.

Naming a Function

While naming a function, it’s important to follow these points:

  • It is recommended that function names begin with an alphabet and be descriptive.
  • It is not appropriate to use spaces or other special characters in function names.
  • The reserved keywords in JavaScript should not be used in the names of functions.

Type of function

There are two types of functions in JavaScript

  1. Built-in Functions
  2. User Defined Functions

Built-in Functions:

The built-in functions are already defined in JavaScript. Some built-in functions are:

  • prompt() : Built-in function to take user input as string
  • parseInt( ): Built-in function to convert to an integer
  • parseFloat( ): Built-in function to convert to a floating-point number
  • isNaN( ): Built-in function to check if something is Not a Number. For a number it returns False, otherwise it returns true
  • alert( ): Used to display data or a message in a box on the window.

User Defined Functions in JavaScript

The functions created by the user to perform a specific task are called user defined functions. In this the user will give:

  • function name
  • parameters written parenthesis
  • code to define the function.
Syntax of user defined functions
function func_name (parameter1, parameter2, parameter3)
 {
 // code to be executed
 return some_result
}
func_name(arg1, arg2, arg3) 

2. Objects

In JavaScript, the objects are like containers that hold related information and actions. Objects help to organise data and make the code reusable. The object has properties and methods. Objects are the fundamental blocks of JavaScript. They are used to

  • Store and organise data
  • Create reusable code.
  • Create complex and powerful applications.
<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>

3. Strings in JavaScript

In JavaScript, a string is a data type used to store text, words and sentences. Strings can be declared using single quotes or double quotes. Every string is made up of characters, which can be alphabets, numbers, symbols or even spaces.

Each and every character in the string has an index number; these index numbers start from 0. Every character of the string has a positive and negative index.

Strings in JavaScript

String Methods

a. str.lenght

“str.length” is used to find the length of the string.

<script>
    var text = "Hello World";
    var length = text.length;
    document.write("The length of the string is: " + length);
</script>

Output:

The length of the string is: 11
b. slice(x, y )

This in-built cuts out part of a string and gives you a new string.

<script>
	var text = "Hello World";
	var result = text.slice(6, 10);
	console.log(result);
</script>

Output:

Worl
c. substring(x, y)

It works as a slice function; only the difference is that it does not accept negative index numbers.

<script>
    var text = "Hello World";
    var part1 = text.substring(6, 9);  

    document.write(part1);
</script>

Output:

Wor  
d. replace(x, y)

Replaces the first match of a character or word.

<script>
	var text = "Hello World";
	var result = text.replace("o", "a");
	console.log(result);
</script>

Output:

Hella World
e. replaceAll(x,y)

Replaces all matches of a character or word.

<script>
	var text = "Hello World";
	var result = text.replaceAll("l", "r");
	console.log(result);
</script>

Output:

Herro Worrd
f. match(string)

Checks if the string matches exactly otherwise, it returns null.

<script>
	var text = "Hello World";
	var result1 = text.match("World");
	console.log(result1);
</script>

Output:

World
g. toUpperCase( )

Converts the whole string to uppercase.

<script>
	var text = "Hello World";
	var result = text.toUpperCase();
	console.log(result);
</script>

Output:

HELLO WORLD
h. toLowerCase()

Converts the whole string to lowercase.

<script>
	var text = "Hello World";
	var result = text.toLowerCase();
	console.log(result);
</script>

Output:

hello world
i. concat(str)

Joins another string to the original one.

<script>
	var text = "Hello World";
	var result1 = text.concat(" Java");
	console.log(result1);
</script>

Output:

Hello World Java
j. trim( )

Removes spaces from both ends of the string.

<script>
	var text = "   Hello World   ";
	var result = text.trim();
	console.log(result);
</script>

Output:

Hello World
k. charAt(n)

Display the character from the specific index number.

<script>
	var text = "Hello World";
	var result = text.charAt(6);
	console.log(result);
</script>

Output:

W

4. Arrays in JavaScript

Array is like a container that can hold several items of data. Arrays can hold various data types like numbers, strings, objects, and even other arrays. Arrays in JavaScript are zero-indexed i.e. the first element is accessed with an index 0, the second element with an index of 1, and so on.

Arrays in JavaScript

There are two ways to create an Array:

  1. Creating an Array using Array Literal:
  2. Creating Array using new keyword:

1. Creating an Array using Array Literal:

Here we simply assign a variable to values written in square bracket [ ], separated with commas.

<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] 

2. Creating Array using new keyword:

In this the keyword new with Array( ) is used to create array

<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] 

Array Methods

a. toString( )

Converts an array into a string of the array values separated by commas.

<script>
    var colors = ['Red', 'Green', 'Blue', 'Yellow'];
    var result = colors.toString();
    document.write("Array as string: " + result);
</script>

Output:

Array as string: Red,Green,Blue,Yellow
b. pop( )

Removes the last element in an array.

<script>
    var colors = ['Red', 'Green', 'Blue', 'Yellow'];
    var removedColor = colors.pop(); 
    document.write("Removed color: " + removedColor);
</script>

Output:

Removed color: Yellow
c. push( )

Adds a new element at the end of the array.

<script>
    var colors = ['Red', 'Green', 'Blue'];
    colors.push('Yellow');
    document.write("Updated array: " + colors);
</script>

Output:

Updated array: Red,Green,Blue,Yellow
d. shift( )

Removes the first element and shifts others left

<script>
    var colors = ['Red', 'Green', 'Blue', 'Yellow'];
    var removedColor = colors.shift(); // Removes 'Red'
    document.write("Removed color: " + removedColor);
</script>

Output:

Removed color: Red
e. unshift( )

Adds a new element to the beginning and shifts others right.

<script>
    var colors = ['Red', 'Green', 'Blue'];
    colors.unshift('Orange');
    document.write("Updated array: " + colors);
</script>

Output:

Updated array: Orange,Red,Green,Blue
f. join( )

Joins all elements into a string with a custom separator.

<script>
    var colors = ['Red', 'Green', 'Blue', 'Yellow'];
    var result = colors.join('&');
    document.write("Joined string: " + result);
</script>

Output:

Joined string: Red&Green&Blue&Yellow
g. concat( )

Merges arrays into a new array.

<script>
    var colors = ['Red', 'Green', 'Blue'];
    var moreColors = ['Yellow', 'Purple'];
    var allColors = colors.concat(moreColors);
    document.write("Combined array: " + allColors);
</script>

Output:

Combined array: Red,Green,Blue,Yellow,Purple
h. slice( )

Returns a portion of the array (does not modify original)

<script>
    var colors = ['Red', 'Green', 'Blue', 'Yellow', 'Purple'];
    var slicedColors = colors.slice(1, 4);
    document.write("Sliced array: " + slicedColors);
</script>

Output:

Sliced array: Green,Blue,Yellow
i. reverse( )

Reverses the array in place

<script>
    var colors = ['Red', 'Green', 'Blue', 'Yellow'];
    colors.reverse();
    document.write("Reversed array: " + colors);
</script>

Output:

Reversed array: Yellow,Blue,Green,Red
j. sort( )

Sorts elements alphabetically (for strings)

<script>
    var colors = ['Red', 'Green', 'Blue', 'Yellow'];
    colors.sort();
    document.write("Sorted array: " + colors);
</script>

Output:

Sorted array: Blue,Green,Red,Yellow

5. Math Methods

Mathematical operations are carried out using the Math object. You can use Math as an object to call all of its methods and properties without having to create it.

a. Math.round(x)

Rounds a number to the nearest integer

<script>
    var num1 = Math.round(5.5);
    var num2 = Math.round(5.49);
    document.write("Math.round(5.5): " + num1 + "<br>");
    document.write("Math.round(5.49): " + num2);
</script>

Output:

Math.round(5.5): 6  
Math.round(5.49): 5

b. Math.ceil(x)

Rounds a number up to the nearest integer

<script>
    var num1 = Math.ceil(5.1);
    var num2 = Math.ceil(5.9);
    document.write("Math.ceil(5.1): " + num1 + "<br>");
    document.write("Math.ceil(5.9): " + num2);
</script>

Output:

Math.ceil(5.1): 6  
Math.ceil(5.9): 6

c. Math.floor(x)

Rounds a number down to the nearest integer

<script>
    var num1 = Math.floor(5.9);
    var num2 = Math.floor(5.1);
    document.write("Math.floor(5.9): " + num1 + "<br>");
    document.write("Math.floor(5.1): " + num2);
</script>

Output:

Math.floor(5.9): 5  
Math.floor(5.1): 5

d. Math.pow(x, y)

Returns the value of x raised to the power y

<script>
    var result = Math.pow(2, 3);
    document.write("Math.pow(2, 3): " + result);
</script>

Output:

Math.pow(2, 3): 8

e. Math.sqrt(x)

Returns the square root of a number

<script>
    var result = Math.pow(2, 3);
    document.write("Math.pow(2, 3): " + result);
</script>

Output:

Math.pow(2, 3): 8

f. Math.min()

Returns the smallest value among the given numbers

<script>
    var smallest = Math.min(5, -2, 8, 1, 2);
    document.write("Smallest value: " + smallest);
</script>

Output:

Smallest value: -2

g. Math.max()

Returns the largest value among the given numbers

<script>
    var largest = Math.max(5, -2, 8, 1, 2);
    document.write("Largest value: " + largest);
</script>

Output:

Largest value: 8

h. Math.random()

Returns a random floating-point number between 0 (inclusive) and 1 (exclusive)

<script>
    var randomValue = Math.random();
    document.write("Random number between 0 and 1: " + randomValue);
</script>

Output:

Random number between 0 and 1: 0.6273849201

6. Events

Event are the actions or occurrence that happen in the browser, often triggered by the user. For example, the onclick event is triggered when the user clicks on an element, and the onload event is triggered when the page is loaded.

EventEvent HandlerDescription
changeonchangeWhen an individual edits the form element’s value.
clickonclickUpon selecting an element with the mouse.
mouseoveronmouseoverWhen the mouse pointer comes over the element.
mouseoutonmouseoutWhen the mouse pointer leaves an element.
keydownonkeydownAs soon as the user presses and releases any key on the keyboard.
loadonloadAfter the browser has finished loading the page.

a. onchange

When an individual edits the form element’s value.

<html>
<body>
  <h3>Type your name:</h3>
  <input type="text" id="nameInput" onchange="showName()">

  <p id="output"></p>

  <script>
    function showName() {
      var name = document.getElementById("nameInput").value;
      document.getElementById("output").innerHTML = "Hello, " + name + "!";
    }
  </script>
</body>
</html>

2. onclick

Upon selecting an element with the mouse.

<html>
  <body>
   <input type="button" value="Click the button" onclick="showName()">

  <script>
    function showName() {
	document.write("Hello!");
    }
  </script>
  </body>
</html>

3. onmouseover

When the mouse pointer comes over the element.

<html>
  <body>
   <input type="button" value="Click the button" onmouseover="showName()">

  <script>
    function showName() {
	document.write("Hello!");
    }
  </script>
  </body>
</html>

4. onmouseout

When the mouse pointer leaves an element.

<html>
  <body>
   <input type="button" value="Click the button" onmouseout="showName()">

  <script>
    function showName() {
	document.write("Hello!");
    }
  </script>
  </body>
</html>

5. onkeydown

As soon as the user presses and releases any key on the keyboard.

<html>
<body>
  <h3>Type something:</h3>
  <input type="text" onkeydown="showKey(event)">
  <p id="output"></p>

  <script>
    function showKey(event) {
      var keyPressed = event.key;
      document.getElementById("output").innerHTML = "You pressed: " + keyPressed;
    }
  </script>
</body>
</html>

6. load

After the browser has finished loading the page.

<html>
<head>
   <script>
    function welcomeMessage() {
      alert("Welcome! The page has fully loaded.");
    }
  </script>
</head>
<body onload="welcomeMessage()">
  <h2>This is a simple page</h2>
</body>
</html>

Disclaimer: We have taken an effort to provide you with the accurate handout of “JavaScript Class 12 Notes“. If you feel that there is any error or mistake, please contact me at anuraganand2017@gmail.com. The above CBSE study material present on our websites is for education purpose, not our copyrights. All the above content and Screenshot are taken from Web Application Class 12 Subject Code 803 CBSE Textbook, Sample Paper, Old Sample Paper, Board Paper and Support Material which is present in CBSEACADEMIC website, This Textbook and Support Material are legally copyright by Central Board of Secondary Education. We are only providing a medium and helping the students to improve the performances in the examination. 

Images and content shown above are the property of individual organizations and are used here for reference purposes only.

For more information, refer to the official CBSE textbooks available at cbseacademic.nic.in

cbseskilleducation

Leave a Comment