Exercise Solutions Available
Step-by-step answers for all textbook questions in this chapter
Chapter 14 — Introduction to Javascript: Exercise Solutions Guide
This page provides complete exercise solutions for Chapter 14: Introduction to Javascript from the Samacheer Kalvi Class 11 Computer Applications textbook. Work through each exercise on your own first, then compare your answers below. Every answer is aligned with the TN State Board syllabus so you can revise quickly before exams.
Key Concepts (Quick Recap)
| Term | Meaning | ||
|---|---|---|---|
| JavaScript | A lightweight, interpreted scripting language that adds interactivity to web pages | ||
| ECMAScript | The official specification/standard that JavaScript follows | ||
| Scripting language | A language that is interpreted at runtime rather than compiled beforehand | ||
| Client-side | Code that runs in the browser on the user's machine (not on the server) | ||
var | Function-scoped variable declaration keyword (older style, can be redeclared) | ||
let | Block-scoped variable declaration keyword (ES6, cannot be redeclared in same scope) | ||
const | Block-scoped declaration for variables that must not be reassigned after initialization | ||
| Number | Primitive data type for numeric values (integers and floating-point) | ||
| String | Primitive data type for textual data enclosed in single, double, or backtick quotes | ||
| Boolean | Primitive data type with only two values: true or false | ||
| Undefined | A variable that has been declared but not assigned a value | ||
| Null | An intentional assignment of "no value"; it is a primitive but typeof null returns "object" | ||
| Object | A complex data type storing key-value pairs; arrays and functions are also objects | ||
| Arithmetic operators | +, -, *, /, %, ++, -- for mathematical calculations | ||
| Comparison operators | ==, ===, !=, !==, <, >, <=, >= to compare values | ||
| Logical operators | && (AND), ` | (OR), !` (NOT) to combine boolean expressions | |
| Assignment operators | =, +=, -=, *=, /=, %= to assign and update variable values | ||
document.write() | Writes output directly into the HTML document stream | ||
console.log() | Prints output to the browser's developer console for debugging | ||
alert() | Displays a pop-up dialog box with a message and an OK button | ||
prompt() | Displays a dialog that asks the user for input; returns the entered string | ||
confirm() | Displays a dialog with OK and Cancel; returns true or false | ||
| DOM | Document Object Model — a tree representation of the HTML page that JavaScript can access and modify | ||
| NaN | "Not-a-Number" — the result of invalid numeric operations (e.g., parseInt("abc")) | ||
| Type coercion | Automatic conversion of a value from one data type to another (e.g., "5" + 1 gives "51") | ||
| String concatenation | Joining strings with the + operator; "Hello" + " World" gives "Hello World" |
I. Choose the Correct Answer (MCQ)
1. JavaScript is a \_\_\_\_\_\_ language.
- (a) Compiled
- (b) Interpreted ✓
- (c) Assembly
- (d) Machine
2. Who created JavaScript?
- (a) Guido van Rossum
- (b) James Gosling
- (c) Brendan Eich ✓
- (d) Dennis Ritchie
3. Where does JavaScript code run?
- (a) On the web server
- (b) In the database
- (c) In the web browser (client-side) ✓
- (d) On the operating system kernel
4. Which keyword declares a block-scoped variable that cannot be redeclared?
- (a)
var - (b)
let✓ - (c)
const - (d)
function
5. Which of the following is NOT a primitive data type in JavaScript?
- (a) Number
- (b) String
- (c) Object ✓
- (d) Boolean
6. What does typeof null return in JavaScript?
- (a)
"null" - (b)
"undefined" - (c)
"object"✓ - (d)
"number"
7. What is the result of "5" + 2 in JavaScript?
- (a)
7 - (b)
"52"✓ - (c)
NaN - (d)
Error
8. Which operator checks both value and type equality?
- (a)
== - (b)
===✓ - (c)
!= - (d)
>=
II. Very Short Answer Questions (2 Marks)
1. What is JavaScript?
JavaScript is a lightweight, interpreted, object-based scripting language developed by Brendan Eich in 1995. It is primarily used to add interactivity and dynamic behaviour to web pages. JavaScript code is embedded in HTML documents and executed by the browser's JavaScript engine. It is different from Java — JavaScript is a scripting language while Java is a full programming language.
2. List any four features of JavaScript.
1. Interpreted — JavaScript code is executed line by line without prior compilation. 2. Lightweight — It has a small footprint and is designed for simple scripting tasks. 3. Object-based — It supports objects but does not support full object-oriented features like classical inheritance. 4. Client-side execution — JavaScript runs in the browser, reducing server load. 5. Case-sensitive — Variable names myVar and myvar are treated as different identifiers.
3. How do you declare a variable in JavaScript? Give examples.
JavaScript provides three keywords to declare variables:
var name = "Kavi"; // function-scoped, can be redeclared
let age = 17; // block-scoped, cannot be redeclared in same scope
const PI = 3.1416; // block-scoped, cannot be reassigned
A variable declared without a keyword becomes a global variable (not recommended). A variable declared without assignment has the value undefined.
4. What are the data types in JavaScript?
JavaScript has two categories of data types:
Primitive types:
- Number — for numeric values (e.g.,
42,3.14) - String — for textual data (e.g.,
"Hello") - Boolean — for
trueorfalse - Undefined — a variable declared but not assigned
- Null — intentional absence of any value
Complex type:
- Object — a collection of key-value pairs; includes arrays and functions as special objects
5. Differentiate between == and === operators.
| Aspect | == (Loose Equality) | === (Strict Equality) |
|---|---|---|
| Checks | Only value (after type coercion) | Both value and type |
| Example | 5 == "5" → true | 5 === "5" → false |
| Recommendation | Avoid in production code | Always preferred |
The == operator converts operands to the same type before comparing, which can produce unexpected results. The === operator does not perform type conversion, making it safer and more predictable.
6. What is the DOM?
The Document Object Model (DOM) is a programming interface provided by the browser. It represents the HTML document as a tree of objects where each element (tag), attribute, and piece of text becomes a node. JavaScript uses the DOM to access, modify, add, or delete HTML elements dynamically.
Example:
document.getElementById("title").innerHTML = "New Title";
This line finds the element with id="title" and changes its content, showing how JavaScript interacts with the DOM.
III. Short Answer Questions (3 Marks)
1. Explain the types of JavaScript operators with examples.
JavaScript operators are classified into the following types:
Arithmetic Operators — perform mathematical calculations:
let a = 10, b = 3;
// a + b → 13 (Addition)
// a - b → 7 (Subtraction)
// a * b → 30 (Multiplication)
// a / b → 3.333... (Division)
// a % b → 1 (Modulus / Remainder)
// a++ → 10 then a becomes 11 (Increment)
// b-- → 3 then b becomes 2 (Decrement)
Comparison Operators — compare two values and return true or false:
// 5 == "5" → true (loose equality)
// 5 === "5" → false (strict equality)
// 5 != 6 → true (loose inequality)
// 5 !== "5" → true (strict inequality)
// 5 > 3 → true
// 5 <= 5 → true
Logical Operators — combine boolean expressions:
// (5 > 3) && (2 < 4) → true (AND — both must be true)
// (5 > 3) || (2 > 4) → true (OR — at least one must be true)
// !(5 > 3) → false (NOT — reverses the result)
Assignment Operators — assign and update values:
let x = 10; // = simple assignment
x += 5; // x = x + 5 → 15
x -= 3; // x = x - 3 → 12
x *= 2; // x = x * 2 → 24
x /= 4; // x = x / 4 → 6
x %= 4; // x = x % 4 → 2
2. Describe any four string methods in JavaScript with examples.
let str = "Hello World";
1. length — returns the number of characters:
str.length; // 11
2. toUpperCase() — converts all characters to uppercase:
str.toUpperCase(); // "HELLO WORLD"
3. toLowerCase() — converts all characters to lowercase:
str.toLowerCase(); // "hello world"
4. charAt(index) — returns the character at the specified position:
str.charAt(0); // "H"
5. indexOf(substring) — returns the first index of the substring, or -1 if not found:
str.indexOf("World"); // 6
6. slice(start, end) — extracts a portion of the string:
str.slice(0, 5); // "Hello"
3. Differentiate between var, let, and const with examples.
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped | Block-scoped |
| Redeclaration | Allowed in same scope | Not allowed | Not allowed |
| Reassignment | Allowed | Allowed | Not allowed |
| Hoisting | Yes (initialized to undefined) | Yes (but not initialized — TDZ) | Yes (but not initialized — TDZ) |
Examples:
function demo() {
var x = 10;
if (true) {
var x = 20; // same variable, overwrites outer x
let y = 30; // block-scoped, only exists inside this if-block
const z = 40; // block-scoped, cannot be reassigned
// z = 50; // Error: Assignment to constant variable
}
console.log(x); // 20 (var is function-scoped)
// console.log(y); // ReferenceError: y is not defined
}
4. Explain the ways to include JavaScript in an HTML document.
There are two ways to include JavaScript in an HTML file:
<script> tag inside HTML:<!DOCTYPE html>
<html>
<head>
<title>Internal JS</title>
</head>
<body>
<h1>My Page</h1>
<script>
document.write("Hello from internal script!");
</script>
</body>
</html>
.js file:<!DOCTYPE html>
<html>
<head>
<title>External JS</title>
<script src="script.js"></script>
</head>
<body>
<h1>My Page</h1>
</body>
</html>
IV. Long Answer Questions (5 Marks)
1. Explain JavaScript data types in detail with examples.
JavaScript data types are divided into two broad categories: primitive and non-primitive (reference) types.
Primitive Data Types:
1. Number — Used for all numeric values, both integers and floating-point. There is no separate integer type.
let age = 17;
let pi = 3.1416;
let negative = -42;
let special = Infinity; // result of 1/0
let notNum = NaN; // result of parseInt("abc")
The value NaN (Not-a-Number) results from invalid numeric operations. typeof NaN is still "number".
2. String — Used for textual data, enclosed in single quotes, double quotes, or backticks.
let greeting = 'Hello';
let name = "Kavitha";
let message = `Welcome, ${name}`; // template literal (ES6)
Strings are immutable — once created, their content cannot be changed in place.
3. Boolean — Represents logical values with only two possibilities:
let isStudent = true;
let hasGraduated = false;
Booleans are commonly used in conditional statements (if, while).
4. Undefined — A variable that has been declared but not assigned a value automatically gets undefined.
let x;
console.log(x); // undefined
console.log(typeof x); // "undefined"
5. Null — Represents the intentional absence of any object value. It is explicitly assigned.
let data = null;
console.log(data); // null
console.log(typeof data); // "object" (historical quirk)
Note: null == undefined is true (loose equality), but null === undefined is false (strict equality).
Non-Primitive (Reference) Data Type:
6. Object — A collection of key-value pairs. Arrays and functions are also objects in JavaScript.
// Object literal
let student = {
name: "Arun",
age: 17,
grade: "11th"
};
// Array (a special kind of object)
let marks = [85, 90, 78, 92, 88];
// Function (also an object)
function greet() {
return "Hello!";
}
The typeof operator is used to determine the data type of a value at runtime:
typeof 42 // "number"
typeof "Hello" // "string"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object"
typeof {} // "object"
typeof [] // "object"
typeof function(){} // "function"
2. Explain JavaScript operators in detail with examples.
JavaScript provides several categories of operators:
3. Explain how to embed JavaScript in HTML with code examples.
JavaScript can be embedded in an HTML document in two primary ways: internal scripting (within the HTML file) and external scripting (linking a separate .js file).
Method 1 — Internal Script using <script> tag:
The <script> tag is placed directly inside the HTML document. It can go in <head> or <body>.
<!DOCTYPE html>
<html>
<head>
<title>Internal JavaScript Example</title>
</head>
<body>
<h1 id="heading">Welcome</h1>
<p id="output"></p>
<script>
// Using document.write()
document.write("<h2>This is written by JavaScript</h2>");
// Using DOM methods
document.getElementById("heading").innerHTML = "Hello, Student!";
// Using console.log() for debugging
console.log("Script is running!");
// Using alert()
alert("This is an alert box!");
// Using prompt()
let name = prompt("Enter your name:");
document.getElementById("output").innerHTML = "Hello, " + name;
</script>
</body>
</html>
Best practice: Place <script> just before </body> so the HTML content loads before the script executes.
Method 2 — External Script using src attribute:
JavaScript code is written in a separate .js file and linked via the <script> tag's src attribute.
File: script.js
function greetUser() {
let name = prompt("What is your name?");
alert("Welcome, " + name + "!");
}
function showSum() {
let a = parseInt(prompt("Enter first number:"));
let b = parseInt(prompt("Enter second number:"));
let sum = a + b;
document.write("The sum is " + sum);
}
File: index.html
<!DOCTYPE html>
<html>
<head>
<title>External JavaScript Example</title>
<script src="script.js"></script>
</head>
<body>
<h1>External Script Demo</h1>
<button onclick="greetUser()">Greet Me</button>
<button onclick="showSum()">Add Numbers</button>
</body>
</html>
Advantages of external scripts: 1. Separation of concerns — HTML structure and JavaScript logic are in different files. 2. Reusability — the same .js file can be linked from multiple HTML pages. 3. Caching — the browser caches the external file, reducing load times on revisit. 4. Maintainability — easier to debug and update when code is in a dedicated file.
Important notes:
- A
<script>tag with asrcattribute should not contain any inline JavaScript code — the inline code is ignored. - JavaScript is case-sensitive:
myVarandmyvarare different variables. - Each JavaScript statement should end with a semicolon (
;) for clarity. - Use
//for single-line comments and/ ... /for multi-line comments.
Common Mistakes to Avoid
1. Confusing JavaScript with Java — They are completely different languages. Java is a compiled, strongly typed language; JavaScript is an interpreted, loosely typed scripting language.
2. Using = instead of == or === in conditions — = assigns a value, == compares values with type coercion, === compares values and types. Writing if (x = 5) assigns 5 to x and always evaluates as truthy.
3. Forgetting that typeof null returns "object" — This is a historical bug in JavaScript. Do not assume null is a separate type when checking with typeof.
4. Mixing string concatenation with arithmetic — "5" + 3 gives "53" (concatenation), not 8. Always convert strings to numbers using parseInt() or Number() when you intend arithmetic.
5. Declaring variables without var, let, or const — Omitting the keyword creates an implicit global variable, which can cause bugs. Always use let or const.
6. Confusing undefined and null — undefined means a variable was declared but never assigned. null is an intentional assignment meaning "no value." They are different: typeof undefined is "undefined", typeof null is "object".
7. Placing <script> in <head> without defer — If the script tries to access DOM elements before the page loads, it will fail. Move scripts to the end of <body> or use the defer attribute.
8. Ignoring case sensitivity — JavaScript is case-sensitive. document.write() works, but Document.Write() does not. Variable names Student and student are different.
Exam Checklist
Before your exam, make sure you can do the following:
- [ ] Define JavaScript and state that it is an interpreted, client-side scripting language created by Brendan Eich
- [ ] List and explain the primitive data types: Number, String, Boolean, Undefined, Null
- [ ] Explain the Object (non-primitive) data type and give examples of objects, arrays
- [ ] Differentiate between
var,let, andconstwith scope, redeclaration, and reassignment - [ ] Write the syntax for all arithmetic operators and predict their output
- [ ] Distinguish between
==(loose equality) and===(strict equality) with examples - [ ] Explain logical operators (
&&,||,!) and construct truth tables - [ ] Use assignment operators (
=,+=,-=,*=,/=,%=) correctly - [ ] Describe string concatenation and type coercion pitfalls (
"5" + 3vs5 + 3) - [ ] Explain how to embed JavaScript in HTML using the
<script>tag (internal and external) - [ ] Use
document.write(),alert(),prompt(), andconsole.log()with correct syntax - [ ] Define the DOM and explain how JavaScript interacts with it using
document.getElementById() - [ ] Explain
NaN,typeofoperator, and whytypeof nullreturns"object" - [ ] Write simple JavaScript programs that accept input, perform calculations, and display output
- [ ] Identify and avoid common mistakes:
=vs==, string concatenation pitfalls, undeclared variables
