JavaScript Class 12 NCERT Solutions are designed to help students understand the core concepts of JavaScript programming as per the CBSE curriculum. These solutions cover all important topics such as variables, data types, operators, functions, events, arrays, objects.
Javascript Class 12 NCERT Solutions
I. Multiple Choice Questions
1. Which of the following statements is not true for JavaScript:
a. JavaScript is a compiled language.
b. In JavaScript an interpreter in the browser reads over the JavaScript code.
c. Any error found in the code, will stop the further execution of the program.
d. JavaScript can be implemented using tags.
2. A script cannot be placed
a. In the body of the page
b. In the header of the page
c. In a file with extension .js
d. In a file with extension .css
3. Which of these in an advantages of JavaScript
a. It can be used for client-side and server-side i.e. front end and back end.
b. It runs on multiple platforms and devices.
c. It is supported by all browsers.
d. All of the above
4. Which of these is not a Primitive Data Type in JavaScript
a. Boolean
b. Undefined
c. Arrays
d. Strings
5. In JavaScript adding a number and a string will return
a. a string
b. a number
c. NaN
d. None of these
6. Which of the following cannot be a variable?
a. _new
b. y24
c. Val
d. 5g
7. Which of the following statements is not true for Variables in JavaScript
a. Variables in JavaScript can be defined using the keyword var.
b. The equal to (=) sign is used to assign a value to a variable.
c. We cannot assign null to a variable.
d. A variable can be undefined.
8. Which of the following is an Arithmetic operator?
a. +=
b. ==
c. +
d. *=
9. When we use a comparison operator the datatype of the output is always:
a. Integer
b. Boolean
c. NaN
d. Undefined
10. What will be the value returned by the following expression?
34 && -10
a. true
b. false
c. 34
d. -10
11. What will be the value returned by the following expression?
0 || -20
a. true
b. false
c. -20
d. 0
12. Which of the following statements is not true for function arguments/parameters?
a. Function parameters are listed between parenthesis ( ).
b. The number of function parameters is fixed.
c. Function arguments are the values that the function receives when it is called.
d. The arguments (parameters) act as local variables within the function.
13. In JavaScript, the definition of a function starts __
a. with the return type, function keyword, function name and parentheses.
b. with the function keyword, function name and parentheses.
c. with the return type, function name and parenthesis.
d. with the function name, parenthesis and return type.
14. For the provided JavaScript code, which of the following is the correct output?
var values=[4,5,6,7]
varans=values.slice(1);
document.write(ans);
a. Error
b. 5, 6, 7
c. 4, 5, 6,
d. 4, 5, 6, 7
15. What will typeof(null) return/output?
a. object
b. null
c. undefined
d. nothing
16. For the JavaScript code provided, which of the following is the correct output?
var values=["Three","Two","One"];
var ans=values.shift();
document.write(ans);
a. One
b. Three
c. Two
d. error
17. Of the following, which method of the Array object is used to extend an array by one or more members and return the array’s new length?
a. splice()
b. unshift()
c. sort()
d. toString()
18. Out of all the built-in methods, which one is used for removing the last element from an array and return it?
a. pop()
b. last()
c. get()
d. shift()
19. Which event occurs when a webpage has finished loading the page?
a. onload
b. onready
c. onloaded
d. unload
20. The syntax for replaceAll( ) is______.
a. string.replaceAll(searchValue, newValue)
b. string.replace(searchValue, newValue)
c. string.replaceall(searchValue, newValue)
d. None of the above
21. What will the following JavaScript code snippet output?
var x="Hello IncludeHelp!";
document.write(x.slice(-13, -1));
a. IncludeHelp!
b. IncludeHelp
c. ValueError
d. Hello,
22. What will the following JavaScript code snippet output?
var myArray=['h','e','l','l','o'];
document.write(myArray[0]);
document.write(myArray[1]);
a. undefined
b. he
c. ValueError
d. TypeError
23. What will the following JavaScript code output?
document.write(Math.ro und(117.5))
a. 117.5
b. 117
c. 118
d. 117.00
24. Which of the following cannot be an output for
document.write(Math.random()*10)
a. 8.49259898
b. 1.78925374
c. 0
d. 10
25. What happens when a user changes the content of a textbox in the following?
a. The user enters the content in the text box.
b. The user gets a message to change the content.
c. The function myFunction( ) gets invoked.
d. The user cannot change the content.
II. List the Built-in function for each of the Following:
1. A function to take user input as string.
Show Answer ⟶2. The function used to convert to an integer.
Show Answer ⟶3. A function to convert to a floating-point number.
Show Answer ⟶4. A function to check if something is Not a Number.
Show Answer ⟶5. Used to display data or a message in a box on the window.
Show Answer ⟶III. Write the events for the following:
1. As soon as the user presses and releases the key.
Show Answer ⟶2. After the browser has finished loading the page.
Show Answer ⟶3. When an individual edits the form element’s value.
Show Answer ⟶4. When the mouse pointer leaves an element.
Show Answer ⟶5. Upon selecting an element with the mouse.
Show Answer ⟶6. When the mouse pointer comes over the element.
Show Answer ⟶IV. What will be the output of the following codes
1.
<html>
<body>
<h2>JavaScript Functions</h2>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
let x = 170;
function myFunction() {
x = 45;
document.getElementById("demo1").innerHTML = x;
document.getElementById("demo2").innerHTML = x + 20;
}
myFunction();
</script>
</body>
</html>
Show Answer ⟶demo2: 65
2.
<html>
<script>
let lang1 = ["HTML", "CSS", "JavaScript"];
let lang2 = ["Python", "C++", "Java"];
lang1 = lang1.concat(lang2);
lang1.sort();
lang1.reverse();
document.write(lang1);
</script>
<body>
</body>
</html>
Show Answer ⟶3.
<html>
<body>
<h2>JavaScript Functions</h2>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
var x = 55;
var y = 45;
function myFunction() {
var x = 100;
var y = 200;
return x + y;
}
document.getElementById("demo2").innerHTML = x + y;
document.getElementById("demo1").innerHTML = myFunction();
</script>
</body>
</html>
Show Answer ⟶demo1: 300 (from local x + y inside function)
4.
<html>
<body>
<p id="Far"></p>
<p id="Cel"></p>
<script>
function toCelsius(temp) {
return (5/9) * (temp - 32);
}
function toFahrenheit(temp) {
return (temp * 9/5) + 32;
}
document.getElementById("Far").innerHTML = toFahrenheit(18);
document.getElementById("Cel").innerHTML = toCelsius(32);
</script>
</body>
</html>
Show Answer ⟶Cel: 0
5.
<html>
<body>
<script>
x = Math.max(66.7, 81.9, -100.5);
y = Math.min(66.7, 81.9, -100.5);
z = Math.ceil(x + y);
document.write(z);
</script>
</body>
</html>
Show Answer ⟶6.
<html>
<body>
<script>
var y = 0;
var p = parseInt(prompt('Enter a no.'));
function checkprime(n) {
for (var x = 2; x < n; x++) {
if (n % x == 0) {
document.write("The number is not prime" + "<br>");
y = 1;
break;
}
}
if (y == 0) {
document.write("The number is prime" + "<br>");
}
}
checkprime(16);
checkprime(23);
</script>
</body>
</html>
Show Answer ⟶The number is prime
VI. Write the code for the following
Write a program with 2 functions to find simple or compound interest depending on user input, also take user input for principal, rate and time.
Answer:
<html>
<body>
<script>
function simpleInterest(p, r, t) {
return (p * r * t) / 100;
}
function compoundInterest(p, r, t) {
return p * Math.pow((1 + r / 100), t) - p;
}
var type = prompt("Enter 'simple' or 'compound' interest:");
var p = parseFloat(prompt("Enter Principal:"));
var r = parseFloat(prompt("Enter Rate (%):"));
var t = parseFloat(prompt("Enter Time (years):"));
var result;
if (type === "simple") {
result = simpleInterest(p, r, t);
} else if (type === "compound") {
result = compoundInterest(p, r, t);
} else {
result = "Invalid type entered.";
}
alert("Interest: " + result);
</script>
</body>
</html>
Write a program where a function MyFunc( ) it takes the user name and displays a message” Hello username welcome to this page!
Answer:
<html>
<body>
<script>
function greetUser(name) {
alert("Hello " + name + " welcome to this page!");
}
var username = prompt("Enter your name:");
greetUser(username);
</script>
</body>
</html>
Write a program with a function to find the smallest out of 3 numbers.
Answer:
<html>
<body>
<script>
function findSmallest(a, b, c) {
return Math.min(a, b, c);
}
var a = parseFloat(prompt("Enter first number:"));
var b = parseFloat(prompt("Enter second number:"));
var c = parseFloat(prompt("Enter third number:"));
alert("Smallest number is: " + findSmallest(a, b, c));
</script>
</body>
</html>
Write a program with a function to take user input in kilograms and convert it to grams. [1 Kilogram=1000 grams]
Answer:
<html>
<body>
<script>
function convertToGrams(kg) {
return kg * 1000;
}
var kg = parseFloat(prompt("Enter weight in kilograms:"));
alert(kg + " kg = " + convertToGrams(kg) + " grams");
</script>
</body>
</html>
Write a program with a function sortnum( ) to sort 3 numbers in ascending order.
Answer:
<html>
<body>
<script>
let a = +prompt("Enter first number");
let b = +prompt("Enter second number");
let c = +prompt("Enter third number");
let numbers = [a, b, c];
numbers.sort((x, y) => x - y);
alert("Sorted numbers: " + numbers);
</script>
</body>
</html>
Using a button call a function Pytha( ) and take the input for the sides then check whether a number is a Pythagorean Triplet or not.
Answer:
<html>
<body>
<h3>Check Pythagorean Triplet</h3>
<button onclick="Pytha()">Check</button>
<script>
function Pytha() {
var a = parseInt(prompt("Enter first side:"));
var b = parseInt(prompt("Enter second side:"));
var c = parseInt(prompt("Enter third side:"));
if (a*a + b*b === c*c || a*a + c*c === b*b || b*b + c*c === a*a) {
alert("Yes, it's a Pythagorean Triplet.");
} else {
alert("No, it's not a Pythagorean Triplet.");
}
}
</script>
</body>
</html>
Write a program with a function called through a button to ask user age and if the age is greater than 18, display the message “You are eligible” in a paragraph.
Answer:
<html>
<body>
<h3>Age Eligibility Checker</h3>
<button onclick="checkAge()">Check Age</button>
<p id="message"></p>
<script>
function checkAge() {
var age = parseInt(prompt("Enter your age:"));
if (age > 18) {
document.getElementById("message").innerText = "You are eligible";
} else {
document.getElementById("message").innerText = "";
}
}
</script>
</body>
</html>
VII. Answer the Following Questions:
Give an example to explain the JavaScript functions and arrays.
Answer: A function is a reusable block of code that can perform a specific task. This function can be defined once and can be used multiple times. An array is a collection of values which can be stored in a single variable. It can hold multiple values like string, number, float, etc.
<html>
<script>
var fruits = ["apple", "banana", "mango"]; // Array
function showFruits(arr) // Function
{
console.log(arr);
}
showFruits(fruits);
</script>
</html>
Describe the JavaScript terms object methods and object properties.
Answer: Objects are the fundamental blocks of JavaScript. They are used to store and organise data, help to create reusable code and are used in complex and powerful applications. Objects use key-value pairs for storing data, for example, name, age, etc. In the obejct properties have values and methods are functions related to the Object that perform a task. Let us consider object as Car and the properties of a Car can be : Colour=Yellow, Shape=Sports, Fuel=Electric
<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>
Using two examples, describe the JavaScript event handler.
Answer: Events can take place whenever there is a change in the state of some object and reacting to events is known as event handling. JavaScript provides event handlers which are functions that are called upon when an event occurs. 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.
Example 1: Click Event
<button onclick="sayHello()">Click Me</button>
<script>
function sayHello() {
alert("Hello!");
}
</script>
Example 2: Mouse Over Event
<p onmouseover="highlight()">Hover here</p>
<script>
function highlight() {
alert("Mouse is over the text!");
}
</script>
Create a JavaScript function that will delete the last element and show the name in uppercase from an array arr1 that was passed to it as an argument.
Answer:
<html>
<body>
<script>
function showNames(arr1) {
arr1.pop(); // Remove the last element
for (var i = 0; i < arr1.length; i++) {
console.log(arr1[i]); // Show names as they are
}
}
var names = ["anurag", "rahul", "priya"];
showNames(names); // Output: anurag, rahul
</script>
</body>
</html>
Differentiate between JavaScript’s ceil and floor methods of the Math Object.
Answer: The Math.ceil() function rounds up to the nearest whole number; like Math.ceil(4.2), the output will be 5, but the Math.floor() function rounds down to the nearest whole number; like Math.floor(4.8), the output will be 4.
Declare a function ‘stringsjava’ in JavaScript to accept two strings arguments. The function should
a. Convert both the strings to lowercase
b. Search for string1 in string2 and display the string if found.
c. Replace all occurrences of letter ‘I’ with ‘ ! ‘ in string2.
d. Display the first character of string1.
Answer:
<html>
<body>
<script>
function stringsjava(str1, str2) {
// a. Convert both strings to lowercase
var s1 = str1.toLowerCase();
var s2 = str2.toLowerCase();
// b. Search for string1 in string2 using indexOf
if (s2.indexOf(s1) !== -1) {
console.log("Found:", s1);
} else {
console.log("Not found");
}
// c. Replace all occurrences of 'I' with ' ! ' in original string2
var replaced = str2.replace(/I/g, " ! ");
console.log("Replaced string2:", replaced);
// d. Display the first character of string1
console.log("First character of string1:", str1.charAt(0));
}
// Example usage
stringsjava("India", "This is INDIA");
</script>
</body>
</html>
Consider the following code:
var cars = [“Honda”, “BMW”, “Audi”, “Porsche”];
Write command in JavaScript to :
a. add an item “Volvo “ to the array cars in the last.
b. remove first element from the array.
c. display number of elements in the array.
d. add following array to an array “cars”.
var person=[“Rajan”, “Yagya”, “Munish”];
Answer:
<html>
<body>
<script>
// Initial array
var cars = ["Honda", "BMW", "Audi", "Porsche"];
// a. Add "Volvo" to the end
cars.push("Volvo");
// b. Remove the first element
cars.shift();
// c. Display number of elements
console.log("Number of elements:", cars.length);
// d. Add another array to cars
var person = ["Rajan", "Yagya", "Munish"];
cars = cars.concat(person);
// Final output
console.log("Updated cars array:", cars);
</script>
</body>
</html>
Consider the string “Life is Beautiful”. Write a function ‘mystring’ that performs the following tasks:
a. Displays the length of the string
b. Displays the string after replacing space “ ” in the string with “ * ”
c. Find the position of the first occurrence of “if” and display it.
Answer:
<html>
<body>
<script>
function mystring() {
var str = "Life is Beautiful";
// a. Display length of the string
console.log("Length of the string:", str.length);
// b. Replace spaces with '*'
var replaced = str.replace(/ /g, "*");
console.log("String after replacing spaces:", replaced);
// c. Find position of first occurrence of "if"
var position = str.indexOf("if");
console.log("Position of 'if':", position);
}
mystring();
</script>
</body>
</html>
Given an array Classes=[“AI”, “ML”, “DS”, “Security”, “RDBMS”]
What will be the output of the following?
a. document.write(Classes.pop( ))
b. document.write(Classes.push(“NoSQL” ))
c. document.write(Classes.unshift(“Prompt”, “UI”)
d. Write the code to output array Classes in the paragraph with ID= “Class”
Answer:
<html>
<body>
<p id="Class"></p>
<script>
// Initial array
var Classes = ["AI", "ML", "DS", "Security", "RDBMS"];
// a. Add "Volvo" to the end
document.write("a. " + Classes.pop() + "<br>"); // Removes "RDBMS" and displays it
// b. Add "NoSQL" to the end
document.write("b. " + Classes.push("NoSQL") + "<br>"); // Adds "NoSQL" and displays new length
// c. Add "Prompt" and "UI" to the beginning
document.write("c. " + Classes.unshift("Prompt", "UI") + "<br>"); // Adds to start and displays new length
// d. Add another array to Classes
var person = ["Rajan", "Yagya", "Munish"];
Classes = Classes.concat(person);
// Display final array in paragraph
document.getElementById("Class").innerText = Classes.join(", ");
</script>
</body>
</html>
Given a string str=’The return statement can be used to return a value at any time’
What will be the output of the following statements?
a. document.write(str.indexOf(‘return’))
b. document.write(str.match(‘to return’))
c. document.write(str.replace(‘value’,’output’))
d. document.write(str.substring(4,10))
Answer:
<html>
<body>
<p id="output"></p>
<script>
var str = "The return statement can be used to return a value at any time";
var result = "";
// a. Display length of the string
result += "a. Length of string: " + str.length + "<br>";
// b. Replace space " " with "*"
var replaced = str.replace(/ /g, "*");
result += "b. After replacing spaces: " + replaced + "<br>";
// c. Find position of first occurrence of "if"
var position = str.indexOf("if");
result += "c. Position of 'if': " + position + "<br>";
// d. Display substring from index 4 to 9 (10 excluded)
var sub = str.substring(4, 10);
result += "d. Substring (4 to 9): " + sub;
// Show all results in paragraph
document.getElementById("output").innerHTML = result;
</script>
</body>
</html>
Disclaimer: We have taken an effort to provide you with the accurate handout of “Javascript Class 12 NCERT Solutions“. 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