10-Mark Questions

Definition: JavaScript statements are instructions executed by the JavaScript engine to perform actions, such as assigning values, controlling flow, or defining logic. Each statement typically ends with a semicolon (;), though JavaScript’s Automatic Semicolon Insertion (ASI) can add them implicitly.

Types of JavaScript Statements:

  1. Declaration Statements: Define variables or functions.
    • var, let, const: Declare variables.
      Example:
      let x = 10;
    • function: Declares a function.
      Example:
      function greet() { return "Hello"; }
  2. Expression Statements: Evaluate to a value and perform an action.
    • Assignment: x = 5;
    • Function call: console.log("Hi");
    • Arithmetic: y = x + 2;
  3. Control Flow Statements: Manage execution order.
    • if, else if, else: Conditional branching.
      Example:
      if (x > 0) { console.log("Positive"); } else { console.log("Non-positive"); }
    • switch: Multi-case branching.
      Example:
      switch (day) {
        case 1: console.log("Monday"); break;
        default: console.log("Other day");
      }
    • for, while, do...while: Loops.
      Example:
      for (let i = 0; i < 3; i++) { console.log(i); }
    • break, continue: Control loop execution.
      Example:
      for (let i = 0; i < 5; i++) { if (i === 3) break; console.log(i); }
  4. Exception Handling Statements: Manage errors.
    • try, catch, finally: Handle errors.
      Example:
      try { let num = 1 / 0; } catch (e) { console.log("Error:", e); }
    • throw: Throws custom errors.
      Example:
      throw new Error("Invalid input");
  5. Other Statements:
    • return: Exits a function with a value.
      Example:
      function sum(a, b) { return a + b; }
    • import, export: Module handling (ES6).
      Example:
      export const pi = 3.14;

Complete Example:

let score = 85;
if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B");
} else {
  console.log("Grade: C");
}
for (let i = 1; i <= 3; i++) {
  console.log("Loop iteration:", i);
}
try {
  if (score < 0) throw new Error("Negative score");
  console.log("Score is valid");
} catch (e) {
  console.log("Error:", e.message);
}

Output:
Grade: B
Loop iteration: 1
Loop iteration: 2
Loop iteration: 3
Score is valid

Conclusion: JavaScript statements include declarations, expressions, control flow, exception handling, and more, enabling dynamic program logic. Mastery of these statements is crucial for writing robust JavaScript code, ensuring high marks in exams.

Definition: An array in JavaScript is a special object used to store multiple values in a single variable, accessed via zero-based indices. Arrays are dynamic, can hold mixed data types, and come with built-in methods for manipulation.

Creating Arrays:

  • Array Literal: let arr = [1, 2, 3];
  • Array Constructor: let arr = new Array(1, 2, 3);
  • Empty Array: let arr = []; or new Array(5); (creates array of length 5).

Properties and Methods:

  1. Properties:
    • length: Returns number of elements.
      Example:
      let arr = [1, 2]; console.log(arr.length); // 2
  2. Accessing/Modifying Elements:
    • Index access: arr[0] retrieves first element.
    • Modify: arr[1] = 5; changes second element.
  3. Common Methods:
    • push(): Adds element to end.
      Example:
      arr.push(4); // [1, 2, 4]
    • pop(): Removes last element.
      Example:
      arr.pop(); // [1, 2]
    • shift(): Removes first element.
      Example:
      arr.shift(); // [2]
    • unshift(): Adds element to start.
      Example:
      arr.unshift(0); // [0, 2]
    • splice(): Adds/removes elements at index.
      Example:
      arr.splice(1, 1, 3); // [0, 3]
    • slice(): Extracts a portion.
      Example:
      let newArr = arr.slice(0, 1); // [0]
    • map(): Applies function to each element.
      Example:
      arr.map(x => x * 2); // [0, 6]
    • filter(): Creates array of elements passing test.
      Example:
      arr.filter(x => x > 0); // [3]
    • reduce(): Reduces array to single value.
      Example:
      arr.reduce((sum, x) => sum + x, 0); // 3

Complete Example:

let fruits = ["Apple", "Banana"];
console.log("Length:", fruits.length); // 2
fruits.push("Orange"); // ["Apple", "Banana", "Orange"]
fruits.pop(); // ["Apple", "Banana"]
fruits[1] = "Mango"; // ["Apple", "Mango"]
let upper = fruits.map(item => item.toUpperCase()); // ["APPLE", "MANGO"]
console.log("Uppercase:", upper);
let filtered = fruits.filter(item => item.length > 5); // ["Mango"]
console.log("Filtered:", filtered);

Output:
Length: 2
Uppercase: ["APPLE", "MANGO"]
Filtered: ["Mango"]

Conclusion: JavaScript arrays are versatile for storing and manipulating data, with dynamic sizing and powerful methods like map, filter, and reduce. Understanding arrays is essential for data handling in JavaScript, ensuring high exam marks.

Definition: A function in JavaScript is a reusable block of code designed to perform a specific task, defined using the function keyword or as expressions. Functions can accept parameters, return values, and support modularity in code.

Types of Functions:

  1. Function Declaration: Named function defined with function.
    Example:
    function add(a, b) { return a + b; }
  2. Function Expression: Function assigned to a variable.
    Example:
    const subtract = function(a, b) { return a - b; };
  3. Arrow Function (ES6): Concise syntax, no own this.
    Example:
    const multiply = (a, b) => a * b;
  4. Immediately Invoked Function Expression (IIFE): Runs immediately.
    Example:
    (function() { console.log("IIFE"); })();
  5. Callback Function: Passed as an argument to another function.
    Example:
    setTimeout(() => console.log("Delayed"), 1000);

Key Features:

  • Parameters: Inputs to functions, with default values (ES6).
    Example: function greet(name = "Guest") { return "Hello, " + name; }
  • Return: Outputs a value; stops execution.
    Example: return x * y;
  • Scope: Variables declared with let/const are block-scoped; var is function-scoped.
  • Closures: Functions retain access to outer scope variables.
    Example:
    function outer() { let x = 10; return function() { return x; }; }
  • Hoisting: Function declarations are hoisted, expressions are not.

Complete Example:

function calculate(a, b, operation = "add") {
  if (operation === "add") return a + b;
  else if (operation === "subtract") return a - b;
  else return a * b;
}
const square = x => x * x;
console.log(calculate(5, 3)); // 8
console.log(calculate(5, 3, "subtract")); // 2
console.log(square(4)); // 16
setTimeout(() => console.log("Callback executed"), 1000);

Output:
8
2
16
(after 1s) Callback executed

Conclusion: JavaScript functions, including declarations, expressions, and arrow functions, enable reusable, modular code. Features like closures, callbacks, and default parameters enhance flexibility, making functions a cornerstone of JavaScript programming, vital for exam success.

5-Mark Questions

Definition: String manipulators in JavaScript are built-in methods and properties used to process, modify, or extract information from strings, which are sequences of characters enclosed in quotes (" ", ' ', or ` `).

Common String Methods:

  • length: Returns string length.
    Example:
    "Hello".length; // 5
  • toUpperCase(), toLowerCase(): Changes case.
    Example:
    "Hello".toUpperCase(); // "HELLO"
  • trim(): Removes whitespace from both ends.
    Example:
    "  Hi  ".trim(); // "Hi"
  • slice(start, end): Extracts a portion.
    Example:
    "Hello".slice(1, 4); // "ell"
  • substring(start, end): Similar to slice.
    Example:
    "Hello".substring(1, 4); // "ell"
  • replace(search, new): Replaces first occurrence.
    Example:
    "Hi all".replace("all", "there"); // "Hi there"
  • split(separator): Splits string into array.
    Example:
    "a,b,c".split(","); // ["a", "b", "c"]
  • indexOf(search): Returns index of first occurrence.
    Example:
    "Hello".indexOf("l"); // 2

Example:

let str = "  JavaScript  ";
console.log(str.length); // 13
console.log(str.trim().toUpperCase()); // "JAVASCRIPT"
console.log(str.slice(3, 7)); // "aScr"
console.log(str.replace("Java", "Type")); // "  TypeScript  "
console.log(str.trim().split("a")); // ["J", "v", "Script"]

Output:
13
JAVASCRIPT
aScr
TypeScript
["J", "v", "Script"]

Conclusion: JavaScript string manipulators like trim, slice, and replace enable efficient string processing. These methods are essential for tasks like text formatting and data parsing, critical for web development and exam answers.

Definition: Mathematical functions in JavaScript are provided by the Math object, a built-in global object containing methods and constants for performing mathematical operations.

Key Mathematical Functions:

  • Math.round(x): Rounds to nearest integer.
    Example:
    Math.round(4.6); // 5
  • Math.floor(x): Rounds down.
    Example:
    Math.floor(4.9); // 4
  • Math.ceil(x): Rounds up.
    Example:
    Math.ceil(4.1); // 5
  • Math.abs(x): Returns absolute value.
    Example:
    Math.abs(-5); // 5
  • Math.pow(base, exponent): Returns base raised to exponent.
    Example:
    Math.pow(2, 3); // 8
  • Math.sqrt(x): Returns square root.
    Example:
    Math.sqrt(16); // 4
  • Math.random(): Returns random number between 0 and 1.
    Example:
    Math.random(); // e.g., 0.723
  • Math.max(...args), Math.min(...args): Returns max/min value.
    Example:
    Math.max(1, 5, 3); // 5

Constants: Math.PI (~3.14159), Math.E (~2.718).

Example:

console.log(Math.round(3.7)); // 4
console.log(Math.floor(3.9)); // 3
console.log(Math.pow(5, 2)); // 25
console.log(Math.sqrt(25)); // 5
console.log(Math.random() * 10); // Random number 0-10
console.log(Math.PI); // 3.141592653589793

Output: Varies for Math.random(), e.g.,
4
3
25
5
7.234
3.141592653589793

Conclusion: The Math object’s functions and constants enable precise mathematical operations in JavaScript, essential for calculations in web applications and exam-ready answers.

Definition: JavaScript is a high-level, interpreted programming language primarily used for adding interactivity to webpages. It runs in browsers (client-side) and on servers (e.g., Node.js), supporting dynamic content and event handling.

Basic Features:

  • Syntax: C-like, with variables, loops, conditionals, and functions.
  • Dynamic Typing: Variables can hold any data type without explicit declaration.
  • Event-Driven: Responds to user actions like clicks or keypresses.
  • DOM Manipulation: Modifies HTML/CSS via the Document Object Model.
  • Asynchronous: Supports callbacks, promises, and async/await for non-blocking operations.

Core Components:

  • Variables: Declared with var, let, or const.
  • Data Types: Number, String, Boolean, Object, Array, etc.
  • Operators: Arithmetic (+, -), comparison (==, ===), logical (&&, ||).
  • Control Structures: if, for, while.
  • Functions: Reusable code blocks.

Example:

let name = "Sudarshan";
if (name.length > 5) {
  console.log("Long name:", name.toUpperCase());
}
for (let i = 1; i <= 3; i++) {
  console.log("Count:", i);
}

Output:
Long name: SUDARSHAN
Count: 1
Count: 2
Count: 3

Conclusion: JavaScript’s basics—variables, data types, operators, control structures, and functions—enable dynamic web development. Understanding these fundamentals is key to mastering JavaScript and scoring well in exams.

Definition: Variables in JavaScript are containers for storing data values, declared using var, let, or const. JavaScript is dynamically typed, so variables can hold any data type without explicit type declaration.

Variable Declarations:

  • var: Function-scoped, hoisted, reassignable.
    Example:
    var x = 10; x = 20;
  • let: Block-scoped, reassignable, not hoisted.
    Example:
    let y = 5; y = 15;
  • const: Block-scoped, cannot be reassigned, not hoisted.
    Example:
    const z = 30; // z = 40; // Error

Key Points:

  • Scope: var is function-scoped; let and const are block-scoped.
  • Hoisting: var declarations are hoisted (initialized as undefined); let and const are not.
  • Reassignment: const prevents reassignment but allows mutable object changes (e.g., arrays).

Example:

var a = 10;
let b = 20;
const c = 30;
if (true) {
  var a = 15; // Same 'a'
  let b = 25; // New 'b'
  console.log(a, b, c); // 15, 25, 30
}
console.log(a, b); // 15, 20
const arr = [1, 2];
arr.push(3); // Allowed
// arr = [4, 5]; // Error

Output:
15 25 30
15 20

Conclusion: JavaScript variables, declared with var, let, or const, provide flexible data storage. Understanding their scope, hoisting, and reassignment rules is crucial for writing reliable code and exam success.

Definition: JavaScript data types define the kind of data a variable can hold. JavaScript is dynamically typed, meaning variables can change types during execution. Data types are divided into primitive and non-primitive types.

Data Types:

  1. Primitive Types:
    • Number: Integers or floats.
      Example: let x = 42; let y = 3.14;
    • String: Text in quotes.
      Example: let str = "Hello";
    • Boolean: true or false.
      Example: let isTrue = true;
    • Undefined: Uninitialized variable.
      Example: let x; // undefined
    • Null: Explicitly no value.
      Example: let x = null;
    • Symbol (ES6): Unique identifiers.
      Example: let sym = Symbol("id");
    • BigInt (ES2020): Large integers.
      Example: let big = 123n;
  2. Non-Primitive Type:
    • Object: Key-value pairs, including arrays and functions.
      Example: let obj = { name: "John" }; let arr = [1, 2];

Type Checking: Use typeof operator.
Example: typeof 42; // "number"

Example:

let num = 100;
let str = "JavaScript";
let bool = false;
let undef;
let nul = null;
let obj = { age: 25 };
let arr = [1, 2, 3];
let sym = Symbol("key");
console.log(typeof num, typeof str, typeof bool, typeof undef, typeof nul, typeof obj, typeof arr, typeof sym);
// number string boolean undefined object object object symbol

Output:
number string boolean undefined object object object symbol

Conclusion: JavaScript’s primitive (Number, String, etc.) and non-primitive (Object) data types enable flexible data handling. Understanding these types and the typeof operator is essential for programming and exam performance.

Definition: HTML, XHTML, and DHTML are web technologies used to create webpages, each with distinct characteristics in structure, syntax, and functionality.

Differences:

Feature HTML XHTML DHTML
Full Form HyperText Markup Language Extensible HyperText Markup Language Dynamic HyperText Markup Language
Purpose Defines webpage structure and content. Stricter, XML-based version of HTML. Enhances HTML with dynamic interactivity.
Syntax Flexible; allows unclosed tags.
Example: <p>Text
Strict; requires well-formed XML.
Example: <p>Text</p>
Combines HTML, CSS, JavaScript.
Example: <div onclick="change()">
Standards HTML5 (current), less rigid. Follows XML rules; XHTML 1.0/1.1. No separate standard; uses HTML/CSS/JS.
Interactivity Static content only. Static, stricter markup. Dynamic via JavaScript and CSS.

Example:

<!-- HTML -->
<p>Hello
<!-- XHTML -->
<p>Hello</p>
<!-- DHTML -->
<div style="color: blue;" onclick="this.style.color='red'">Click me</div>
<script>
function change() { document.querySelector('div').style.color = 'red'; }
</script>

Conclusion: HTML provides basic webpage structure, XHTML enforces stricter XML-based markup, and DHTML adds dynamic interactivity using HTML, CSS, and JavaScript. Understanding their differences is key for web development and exam answers.