10 Marks Questions

Definition: Data validation in JavaScript is the process of checking user input or data to ensure it meets specific criteria (e.g., format, type, range) before processing, preventing errors or security issues in web applications.

Purpose:

  • Ensures data integrity and correctness.
  • Prevents invalid submissions (e.g., empty fields, wrong formats).
  • Enhances user experience with clear error messages.
  • Protects against malicious input (e.g., SQL injection, XSS).

Techniques:

  1. Client-Side Validation: Performed in the browser using JavaScript and HTML attributes (e.g., required, pattern).
  2. Server-Side Validation: Essential for security, done on the server (complements client-side).
  3. Regular Expressions: Validate formats like email or phone numbers.
  4. Type Checking: Ensure correct data types (e.g., number, string).
  5. Range Checking: Verify values within acceptable limits.

Complete Example: A form validating name (non-empty), email (valid format), and age (18–100).

<html>
<head>
  <style>
    .error { color: red; }
    .success { color: green; }
  </style>
</head>
<body>
  <form id="myForm">
    <label>Name: <input type="text" id="name"></label>
    <p id="nameError" class="error"></p>
    <label>Email: <input type="email" id="email"></label>
    <p id="emailError" class="error"></p>
    <label>Age: <input type="number" id="age"></label>
    <p id="ageError" class="error"></p>
    <button type="submit">Submit</button>
  </form>
  <p id="success" class="success"></p>
  <script>
    document.getElementById("myForm").addEventListener("submit", function(e) {
      e.preventDefault();
      let isValid = true;
      // Name validation
      const name = document.getElementById("name").value.trim();
      const nameError = document.getElementById("nameError");
      if (name === "") {
        nameError.textContent = "Name is required";
        isValid = false;
      } else {
        nameError.textContent = "";
      }
      // Email validation
      const email = document.getElementById("email").value.trim();
      const emailError = document.getElementById("emailError");
      const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!emailRegex.test(email)) {
        emailError.textContent = "Invalid email format";
        isValid = false;
      } else {
        emailError.textContent = "";
      }
      // Age validation
      const age = parseInt(document.getElementById("age").value);
      const ageError = document.getElementById("ageError");
      if (isNaN(age) || age < 18 || age > 100) {
        ageError.textContent = "Age must be between 18 and 100";
        isValid = false;
      } else {
        ageError.textContent = "";
      }
      // Success message
      const success = document.getElementById("success");
      if (isValid) {
        success.textContent = "Form submitted successfully!";
      } else {
        success.textContent = "";
      }
    });
  </script>
</body>
</html>

Output: Displays error messages for invalid inputs (e.g., empty name, invalid email, age < 18) or a success message if all inputs are valid.

Conclusion: Data validation ensures reliable data processing in JavaScript applications. Using techniques like regex, type checking, and HTML attributes, as shown in the form example, is critical for user experience and security, ensuring high exam marks.

Definition: Exception handling in JavaScript is the process of managing errors (exceptions) that occur during code execution, using try, catch, finally, and throw statements to ensure robust and graceful error recovery.

Key Components:

  1. try: Encloses code that might throw an error.
    try { /* risky code */ }
  2. catch: Handles the error if one occurs.
    catch (error) { /* handle error */ }
  3. finally: Executes code regardless of error (optional).
    finally { /* cleanup code */ }
  4. throw: Generates custom errors.
    throw new Error("Message");

Error Object: Contains name (e.g., TypeError, ReferenceError) and message properties.

Common Errors:

  • SyntaxError: Invalid code syntax.
  • ReferenceError: Undefined variable.
  • TypeError: Invalid operation on a type.

Complete Example: A function dividing two numbers with error handling.

function divide(a, b) {
  try {
    if (b === 0) {
      throw new Error("Division by zero is not allowed");
    }
    if (isNaN(a) || isNaN(b)) {
      throw new TypeError("Inputs must be numbers");
    }
    const result = a / b;
    console.log("Result:", result);
    return result;
  } catch (error) {
    console.log("Error:", error.name, "-", error.message);
    return null;
  } finally {
    console.log("Division operation completed");
  }
}
divide(10, 2); // Result: 5, Division operation completed
divide(10, 0); // Error: Error - Division by zero, Division operation completed null
divide("10", null); // Error: TypeError - Inputs must be numbers, Division operation completed null

Output:
Result: 5
Division operation completed
Error: Error - Division by zero is not allowed
Division operation completed
null
Error: TypeError - Inputs must be numbers
Division operation completed
null

Conclusion: Exception handling in JavaScript, using try, catch, finally, and throw, ensures robust applications by gracefully managing errors. The example demonstrates error detection and recovery, critical for reliable code and exam success.

Definition: Regular expressions (regex) in JavaScript are powerful patterns used to match and manipulate strings, defined using literal notation (/pattern/flags) or the RegExp constructor, commonly used for validation, searching, and replacing text.

Components:

  • Patterns: Define the match (e.g., \d for digits, [a-z] for lowercase letters).
  • Flags: Modify behavior (e.g., i for case-insensitive, m for multiline).
  • Quantifiers: Specify repetitions (e.g., * (0+), + (1+), ? (0 or 1)).
  • Anchors: Match positions (e.g., ^ for start, $ for end).

Common Methods:

  • test(): Checks if pattern matches.
    Example:
    /\d/.test("123"); // true
  • exec(): Returns match details.
    Example:
    /\d/.exec("abc1"); // ["1"]
  • match(): Returns all matches.
    Example:
    "a1b2".match(/\d/g); // ["1", "2"]
  • replace(): Replaces matches.
    Example:
    "abc".replace(/b/, "x"); // "axc"

Complete Example: Validating email and extracting digits.

const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test("user@domain.com")); // true
console.log(emailRegex.test("invalid.email")); // false
const text = "My numbers are 123 and 456";
const digitRegex = /\d+/g;
const digits = text.match(digitRegex);
console.log("Digits:", digits); // ["123", "456"]
const replaced = text.replace(digitRegex, "X");
console.log("Replaced:", replaced); // My numbers are X and X

Output:
true
false
Digits: ["123", "456"]
Replaced: My numbers are X and X

Conclusion: Regular expressions in JavaScript enable precise string matching and manipulation, vital for tasks like validation and data extraction. The example demonstrates their power, ensuring high marks in exams.

Definition: Built-in objects in JavaScript are pre-defined objects provided by the JavaScript engine, offering properties and methods for common tasks like string manipulation, math operations, date handling, and more.

Common Built-in Objects:

  1. Object: Base object for all objects.
    • Methods: Object.keys(), Object.values().
    • Example:
      let obj = {a: 1}; console.log(Object.keys(obj)); // ["a"]
  2. Array: Manages ordered collections.
    • Methods: push(), map(), filter().
    • Example:
      let arr = [1, 2]; arr.push(3); // [1, 2, 3]
  3. String: Handles text.
    • Methods: toUpperCase(), slice().
    • Example:
      "hi".toUpperCase(); // "HI"
  4. Math: Performs mathematical operations.
    • Methods: Math.random(), Math.floor().
    • Example:
      Math.floor(4.7); // 4
  5. Date: Manages dates and times.
    • Methods: getFullYear(), setDate().
    • Example:
      new Date().getFullYear(); // 2025
  6. RegExp: Handles regular expressions.
    • Methods: test(), exec().
    • Example:
      /\d/.test("1"); // true
  7. JSON: Parses and stringifies JSON data.
    • Methods: JSON.parse(), JSON.stringify().
    • Example:
      JSON.stringify({a: 1}); // '{"a":1}'

Complete Example:

let data = { name: "Sudarshan", age: 20 };
console.log(Object.keys(data)); // ["name", "age"]
let arr = ["a", "b"];
arr.push("c");
console.log(arr); // ["a", "b", "c"]
let str = "hello";
console.log(str.toUpperCase()); // "HELLO"
console.log(Math.random()); // e.g., 0.723
let now = new Date();
console.log(now.getFullYear()); // 2025
let regex = /\d/;
console.log(regex.test("123")); // true
let json = JSON.stringify(data);
console.log(json); // '{"name":"Sudarshan","age":20}'

Output:
["name", "age"]
["a", "b", "c"]
HELLO
0.723 (varies)
2025
true
{"name":"Sudarshan","age":20}

Conclusion: Built-in objects like Array, Math, and Date provide essential functionality in JavaScript. Understanding their methods, as shown in the example, is key for efficient programming and exam success.

5-Mark Questions

Definition: Opening a new window in JavaScript involves using the window.open() method to create a new browser window or tab, allowing control over its URL, size, and features.

Syntax:
window.open(url, name, features);

  • url: The URL to load (e.g., "https://example.com").
  • name: Window name (e.g., "_blank" for new tab).
  • features: Comma-separated settings (e.g., "width=500,height=400").

Features: width, height, top, left, menubar, toolbar, resizable.

Example:

<html>
<body>
  <button onclick="openWindow()">Open New Window</button>
  <script>
    function openWindow() {
      const newWindow = window.open(
        "https://example.com",
        "_blank",
        "width=600,height=400,top=100,left=100,resizable=yes"
      );
      if (newWindow) {
        newWindow.focus();
      } else {
        alert("Popup blocked! Allow popups for this site.");
      }
    }
  </script>
</body>
</html>

Output: Clicking the button opens a new window (600x400 pixels) at position (100,100) loading "https://example.com". If popups are blocked, an alert is shown.

Notes:

  • Modern browsers may block popups by default.
  • Use newWindow.focus() to bring the window to front.
  • newWindow.close() can close the window.

Conclusion: The window.open() method enables opening new windows with customizable features, as shown in the example. Understanding its usage is essential for web interactivity and exam answers.

Definition: Dialog boxes in JavaScript are modal windows that interact with users, displaying messages, collecting input, or confirming actions. They are created using the window object’s alert, confirm, and prompt methods.

Types of Dialog Boxes:

  1. Alert Dialog Box:
    • Displays a message with an "OK" button.
    • Syntax: alert(message);
    • Use: Inform users of errors, warnings, or information.
    • Example:
      alert("Form submitted successfully!");
  2. Confirmation Dialog Box:
    • Displays a message with "OK" and "Cancel" buttons.
    • Syntax: confirm(message);
    • Returns: true (OK) or false (Cancel).
    • Use: Confirm user actions (e.g., delete).
    • Example:
      let result = confirm("Are you sure?"); // true or false
  3. Prompt Dialog Box:
    • Displays a message, input field, and "OK"/"Cancel" buttons.
    • Syntax: prompt(message, defaultValue);
    • Returns: User input (string) or null (Cancel).
    • Use: Collect user input.
    • Example:
      let name = prompt("Enter your name:", "Guest");

Complete Example:

<html>
<body>
  <button onclick="showDialogs()">Show Dialogs</button>
  <p id="output"></p>
  <script>
    function showDialogs() {
      alert("Welcome to the dialog demo!");
      let confirmResult = confirm("Do you want to continue?");
      let output = document.getElementById("output");
      if (confirmResult) {
        let userInput = prompt("Enter your feedback:", "Great");
        if (userInput !== null) {
          output.textContent = "Feedback: " + userInput;
        } else {
          output.textContent = "Prompt cancelled";
        }
      } else {
        output.textContent = "Confirmation cancelled";
      }
    }
  </script>
</body>
</html>

Output: Shows an alert, then a confirmation dialog. If "OK" is clicked, a prompt appears; the output displays the user’s feedback or cancellation message.

Conclusion: JavaScript dialog boxes (alert, confirm, prompt) facilitate user interaction, as shown in the example. They are simple yet effective for web applications, ensuring clarity in exam answers.