Current Affairs updated daily
KalviGavaniKalviGavani
Class 11 · Tamil Nadu State Board

Introduction to Javascript Exercise Solutions | KalviGavani

TN Class 11 Computer Applications Introduction to Javascript exercise solutions — variables, data types, operators, statements, DOM, scripting, MCQ and long answers.

Updated 16 June 202619 min read

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)

TermMeaning
JavaScriptA lightweight, interpreted scripting language that adds interactivity to web pages
ECMAScriptThe official specification/standard that JavaScript follows
Scripting languageA language that is interpreted at runtime rather than compiled beforehand
Client-sideCode that runs in the browser on the user's machine (not on the server)
varFunction-scoped variable declaration keyword (older style, can be redeclared)
letBlock-scoped variable declaration keyword (ES6, cannot be redeclared in same scope)
constBlock-scoped declaration for variables that must not be reassigned after initialization
NumberPrimitive data type for numeric values (integers and floating-point)
StringPrimitive data type for textual data enclosed in single, double, or backtick quotes
BooleanPrimitive data type with only two values: true or false
UndefinedA variable that has been declared but not assigned a value
NullAn intentional assignment of "no value"; it is a primitive but typeof null returns "object"
ObjectA 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
DOMDocument 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 coercionAutomatic conversion of a value from one data type to another (e.g., "5" + 1 gives "51")
String concatenationJoining 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
ExplanationJavaScript is an interpreted scripting language. The browser's JavaScript engine reads and executes the code line by line at runtime; it is not compiled into machine code beforehand.

2. Who created JavaScript?

  • (a) Guido van Rossum
  • (b) James Gosling
  • (c) Brendan Eich ✓
  • (d) Dennis Ritchie
ExplanationBrendan Eich created JavaScript in 1995 at Netscape Communications. Guido van Rossum created Python, James Gosling created Java, and Dennis Ritchie created C.

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
ExplanationJavaScript was originally designed as a client-side scripting language that runs inside the browser. While Node.js enables server-side JS, the textbook focuses on browser-based execution.

4. Which keyword declares a block-scoped variable that cannot be redeclared?

  • (a) var
  • (b) let ✓
  • (c) const
  • (d) function
Explanationlet is block-scoped and cannot be redeclared in the same scope. var is function-scoped and can be redeclared. const is also block-scoped but additionally prevents reassignment. function is not a variable declaration keyword.

5. Which of the following is NOT a primitive data type in JavaScript?

  • (a) Number
  • (b) String
  • (c) Object ✓
  • (d) Boolean
ExplanationObject is a complex (non-primitive) data type. The primitive types in JavaScript are Number, String, Boolean, Undefined, Null, Symbol, and BigInt.

6. What does typeof null return in JavaScript?

  • (a) "null"
  • (b) "undefined"
  • (c) "object" ✓
  • (d) "number"
Explanationtypeof null returns "object". This is a well-known historical bug in JavaScript that has been retained for backward compatibility.

7. What is the result of "5" + 2 in JavaScript?

  • (a) 7
  • (b) "52" ✓
  • (c) NaN
  • (d) Error
ExplanationWhen the + operator is used with a string, JavaScript performs type coercion and converts the number to a string, then concatenates them: "5" + "2" gives "52".

8. Which operator checks both value and type equality?

  • (a) ==
  • (b) === ✓
  • (c) !=
  • (d) >=
ExplanationThe strict equality operator === checks both value and type. The loose equality operator == checks only value after performing type coercion. For example, 5 == "5" is true but 5 === "5" is false.

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 true or false
  • 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)
ChecksOnly value (after type coercion)Both value and type
Example5 == "5" → true5 === "5" → false
RecommendationAvoid in production codeAlways 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.

Featurevarletconst
ScopeFunction-scopedBlock-scopedBlock-scoped
RedeclarationAllowed in same scopeNot allowedNot allowed
ReassignmentAllowedAllowedNot allowed
HoistingYes (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:

1. Internal / Inline Script — using the <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>
Answer

The <script> tag can be placed in <head> or <body>. Placing it just before </body> ensures the HTML loads first.

2. External Script — linking a separate .js file:
<!DOCTYPE html>
<html>
<head>
  <title>External JS</title>
  <script src="script.js"></script>
</head>
<body>
  <h1>My Page</h1>
</body>
</html>
Answer

The file script.js contains the JavaScript code without any <script> tags. External scripts promote code reuse, easier maintenance, and browser caching.


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:

1. Arithmetic Operators:
Answer

These perform mathematical operations on numeric operands.

let a = 15, b = 4;
console.log(a + b);   // 19  (Addition)
console.log(a - b);   // 11  (Subtraction)
console.log(a * b);   // 60  (Multiplication)
console.log(a / b);   // 3.75 (Division — always returns floating point)
console.log(a % b);   // 3   (Modulus — remainder after division)
console.log(a++);      // 15  (Post-increment: returns value, then adds 1)
console.log(--b);      // 3   (Pre-decrement: subtracts 1, then returns value)
2. Comparison Operators:
Answer

These compare two values and return a Boolean result.

let x = 5, y = "5";
console.log(x == y);    // true   (loose equality — value only, type coerced)
console.log(x === y);   // false  (strict equality — value AND type)
console.log(x != y);    // false   (loose inequality)
console.log(x !== y);   // true   (strict inequality)
console.log(x > 3);     // true   (greater than)
console.log(x < 3);     // false  (less than)
console.log(x >= 5);    // true   (greater than or equal to)
console.log(x <= 4);    // false  (less than or equal to)
3. Logical Operators:
Answer

These combine or invert Boolean expressions.

let age = 18, hasID = true;
console.log(age >= 18 && hasID);   // true  (AND — both conditions true)
console.log(age >= 21 || hasID);   // true  (OR — at least one condition true)
console.log(!hasID);                // false (NOT — reverses Boolean value)

Truth table summary:

ABA && BA \\B!A
TTTTF
TFFTF
FTFTT
FFFFT
4. Assignment Operators:
Answer

These assign values to variables, often with an arithmetic operation combined.

let n = 20;
n += 5;   // n = n + 5  → 25
n -= 10;  // n = n - 10 → 15
n *= 2;   // n = n * 2  → 30
n /= 3;   // n = n / 3  → 10
n %= 3;   // n = n % 3  → 1
5. String Concatenation Operator:
Answer

The + operator, when used with strings, performs concatenation.

let first = "Samacheer";
let last = "Kalvi";
let full = first + " " + last;  // "Samacheer Kalvi"

// Type coercion example
"Value: " + 10;   // "Value: 10" (number coerced to string)
"5" + 3;          // "53" (number coerced, then concatenated)
"5" - 3;          // 2   (string coerced to number for subtraction)
6. Conditional (Ternary) Operator:
Answer

A shorthand for if-else that returns a value.

let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";
// status → "Adult"

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 a src attribute should not contain any inline JavaScript code — the inline code is ignored.
  • JavaScript is case-sensitive: myVar and myvar are 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, and const with 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" + 3 vs 5 + 3)
  • [ ] Explain how to embed JavaScript in HTML using the <script> tag (internal and external)
  • [ ] Use document.write(), alert(), prompt(), and console.log() with correct syntax
  • [ ] Define the DOM and explain how JavaScript interacts with it using document.getElementById()
  • [ ] Explain NaN, typeof operator, and why typeof null returns "object"
  • [ ] Write simple JavaScript programs that accept input, perform calculations, and display output
  • [ ] Identify and avoid common mistakes: = vs ==, string concatenation pitfalls, undeclared variables

Frequently Asked Questions

JavaScript is a lightweight, interpreted scripting language used to make web pages interactive. It runs in the browser and can manipulate HTML and CSS dynamically.
← Browse all Class 11 Exercise Solutions

More exercise solutions