- JavaScript Pre-defined and User-defined Objects
 a. Write a program using document object properties and methods.
 b. Write a program using window object properties and methods.
 c. Write a program using array object properties and methods.
 d. Write a program using math object properties and methods.
 e. Write a program using string object properties and methods.
 f. Write a program using regex object properties and methods.
 g. Write a program using date object properties and methods.
 h. Write a program to explain user-defined object by using properties, methods, accessors, constructors and display.
a. Write a program using document object properties and methods.
</>
                        Copy
                        <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My College - Student Details</title>
  <script>
    // User-defined object constructor for Student
    function Student(name, id, branch) {
      this.name = name;
      this.id = id;
      this.branch = branch;
      // Method to display student details using document methods
      this.displayDetails = function() {
        // Create a div element to hold the student details
        var studentDiv = document.createElement('div');
        studentDiv.innerHTML = '<h2>Student Details</h2>' +
                               '<p><strong>Name:</strong> ' + this.name + '</p>' +
                               '<p><strong>ID:</strong> ' + this.id + '</p>' +
                               '<p><strong>Branch:</strong> ' + this.branch + '</p>';
        // Append the div to the body using the pre-defined document object
        document.body.appendChild(studentDiv);
      }
    }
    // Use window.onload to run code after the document is fully loaded
    window.onload = function() {
      // Create a header element using a document method
      var header = document.createElement('h1');
      header.textContent = 'My College - Student Details';
      document.body.appendChild(header);
      // Create an instance of the user-defined Student object
      var student1 = new Student("Arjun", "A001", "Computer Science");
      
      // Call the method to display the student's details
      student1.displayDetails();
      // Create a paragraph element to provide additional information
      var infoPara = document.createElement('p');
      infoPara.textContent = 'For more information, visit admin department.';
      document.body.appendChild(infoPara);
    }
  </script>
</head>
<body>
</body>
</html>
Explanation
User-defined Object (Student):
The Student constructor function creates an object with properties (name, id, major) and a method (displayDetails) that generates HTML content using the document’s methods.
Pre-defined Document Object:
The code uses various document object methods:
- document.createElement()to create new HTML elements.
- document.body.appendChild()to insert these elements into the page.
- Direct manipulation of element properties (like innerHTMLandtextContent) to set content.
b. Write a program using window object properties and methods.
</>
                        Copy
                        <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My College - Student Details</title>
  <script>
    // User-defined object constructor for Student
    function Student(name, id, branch) {
      this.name = name;
      this.id = id;
      this.branch = branch;
      // Method to display student details using document methods
      this.displayDetails = function() {
        // Create a div element to hold the student details
        var studentDiv = document.createElement('div');
        studentDiv.innerHTML = '<h2>Student Details</h2>' +
                               '<p><strong>Name:</strong> ' + this.name + '</p>' +
                               '<p><strong>ID:</strong> ' + this.id + '</p>' +
                               '<p><strong>Branch:</strong> ' + this.branch + '</p>';
        // Append the div to the body using the pre-defined document object
        document.body.appendChild(studentDiv);
      }
    }
    // Use window.onload to run code after the document is fully loaded
    window.onload = function() {
      // Create a header element using a document method
      var header = document.createElement('h1');
      header.textContent = 'My College - Student Details';
      document.body.appendChild(header);
      // Create an instance of the user-defined Student object
      var student1 = new Student("Arjun", "A001", "Computer Science");
      
      // Call the method to display the student's details
      student1.displayDetails();
      // Create a paragraph element to provide additional information
      var infoPara = document.createElement('p');
      infoPara.textContent = 'For more information, visit admin department.';
      document.body.appendChild(infoPara);
      // ----- Demonstration of window object properties and methods -----
      // Display the current URL using window.location.href
      var urlPara = document.createElement('p');
      urlPara.textContent = 'Current URL: ' + window.location.href;
      document.body.appendChild(urlPara);
      // Create a button to display window dimensions using window.innerWidth and window.innerHeight
      var sizeButton = document.createElement('button');
      sizeButton.textContent = 'Show Window Size';
      sizeButton.onclick = function() {
        alert('Window Size - Width: ' + window.innerWidth + 'px, Height: ' + window.innerHeight + 'px');
      };
      document.body.appendChild(sizeButton);
      // Create another button that opens a new window using window.open()
      var newWindowButton = document.createElement('button');
      newWindowButton.textContent = 'Open New Window';
      newWindowButton.onclick = function() {
        // Open a new window with a simple HTML content
        var newWin = window.open("", "NewWindow", "width=400,height=300");
        newWin.document.write("<h2>Welcome to the new window!</h2><p>This window was opened using window.open()</p>");
      };
      document.body.appendChild(newWindowButton);
    }
  </script>
</head>
<body>
</body>
</html>
Explanation
- Student Object:
 TheStudentconstructor remains as before, allowing us to create a student instance and display its details.
- window.onload:
 This property ensures that the code runs only after the document is fully loaded.
- window.location.href:
 A new paragraph is created to display the current URL of the page.
- Window Dimensions Button:
 A button is added that, when clicked, shows the browser’s current width and height usingwindow.innerWidthandwindow.innerHeight.
- New Window Button:
 Another button uses thewindow.open()method to open a new window with some sample HTML content.

Click on Show Window Size button.

Click on OK button to close the alert.
Now, click on Open New Window button.

c. Write a program using array object properties and methods.
</>
                        Copy
                        <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My College - Student Details</title>
  <script>
    // User-defined object constructor for Student
    function Student(name, id, branch) {
      this.name = name;
      this.id = id;
      this.branch = branch;
      // Method to display student details using document methods
      this.displayDetails = function() {
        // Create a div element to hold the student details
        var studentDiv = document.createElement('div');
        studentDiv.innerHTML = '<h2>Student Details</h2>' +
                               '<p><strong>Name:</strong> ' + this.name + '</p>' +
                               '<p><strong>ID:</strong> ' + this.id + '</p>' +
                               '<p><strong>Branch:</strong> ' + this.branch + '</p>';
        // Append the div to the body using the pre-defined document object
        document.body.appendChild(studentDiv);
      }
    }
    // Use window.onload to run code after the document is fully loaded
    window.onload = function() {
      // Create a header element using a document method
      var header = document.createElement('h1');
      header.textContent = 'My College - Student Details';
      document.body.appendChild(header);
      // Create an instance of the user-defined Student object
      var student1 = new Student("Arjun", "A001", "Computer Science");
      
      // Call the method to display the student's details
      student1.displayDetails();
      // Create a paragraph element to provide additional information
      var infoPara = document.createElement('p');
      infoPara.textContent = 'For more information, visit admin department.';
      document.body.appendChild(infoPara);
      // --------- Array Object Properties and Methods Demonstration ---------
      // Section header for Array Operations
      var arrayHeader = document.createElement('h2');
      arrayHeader.textContent = 'Array Object Properties and Methods';
      document.body.appendChild(arrayHeader);
      // Initialize an array of student names
      var studentNames = ["Arjun", "Aisha", "Rohan", "Priya"];
      // Display the initial array using join()
      var initialArrayPara = document.createElement('p');
      initialArrayPara.textContent = 'Initial Array: ' + studentNames.join(", ");
      document.body.appendChild(initialArrayPara);
      // Display the length property of the array
      var lengthPara = document.createElement('p');
      lengthPara.textContent = 'Array Length: ' + studentNames.length;
      document.body.appendChild(lengthPara);
      // Add a new student name using the push() method
      studentNames.push("Suresh");
      var pushPara = document.createElement('p');
      pushPara.textContent = 'After push("Suresh"): ' + studentNames.join(", ");
      document.body.appendChild(pushPara);
      // Remove the last element using the pop() method
      var removedName = studentNames.pop();
      var popPara = document.createElement('p');
      popPara.textContent = 'After pop(), removed: ' + removedName + '. Array now: ' + studentNames.join(", ");
      document.body.appendChild(popPara);
      // Sort the array using the sort() method
      studentNames.sort();
      var sortPara = document.createElement('p');
      sortPara.textContent = 'After sort(): ' + studentNames.join(", ");
      document.body.appendChild(sortPara);
      // Reverse the array using the reverse() method
      studentNames.reverse();
      var reversePara = document.createElement('p');
      reversePara.textContent = 'After reverse(): ' + studentNames.join(", ");
      document.body.appendChild(reversePara);
      // Join array elements into a string using the join() method with a custom separator
      var joinStr = studentNames.join(" - ");
      var joinPara = document.createElement('p');
      joinPara.textContent = 'Using join(" - "): ' + joinStr;
      document.body.appendChild(joinPara);
    }
  </script>
</head>
<body>
</body>
</html>Explanation
- Student Object:
 TheStudentconstructor function creates a user‐defined object with properties (name,id,branch) and a method (displayDetails) that uses document methods to display student details.
- Array Operations Section:
 A new section titled “Array Object Properties and Methods” is added:- Initialization: An array named studentNamesis created.
- Display & Length: The initial contents and the length of the array are displayed.
- push() Method: A new element (“Suresh”) is added, and the updated array is shown.
- pop() Method: The last element is removed, and the removed element along with the new array state is displayed.
- sort() & reverse() Methods: The array is sorted alphabetically, then reversed.
- join() Method: The array elements are combined into a string using a custom separator.
 
- Initialization: An array named 

d. Write a program using math object properties and methods.
</>
                        Copy
                        <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My College - Student Details</title>
  <script>
    // User-defined object constructor for Student
    function Student(name, branch, marks, totalMarks) {
      this.name = name;
      // Generate a random user id using Math.random() and Math.floor()
      this.id = "A" + Math.floor(Math.random() * 1000);
      this.branch = branch;
      this.marks = marks;
      this.totalMarks = totalMarks;
      // Calculate percentage and round it to the nearest integer using Math.round()
      this.percentage = Math.round((marks / totalMarks) * 100);
      // Method to display student details using document methods
      this.displayDetails = function() {
        // Create a div element to hold the student details
        var studentDiv = document.createElement('div');
        studentDiv.innerHTML = '<h2>Student Details</h2>' +
                               '<p><strong>Name:</strong> ' + this.name + '</p>' +
                               '<p><strong>ID:</strong> ' + this.id + '</p>' +
                               '<p><strong>Branch:</strong> ' + this.branch + '</p>' +
                               '<p><strong>Marks:</strong> ' + this.marks + ' out of ' + this.totalMarks + '</p>' +
                               '<p><strong>Percentage:</strong> ' + this.percentage + '%</p>';
        // Append the div to the body using the pre-defined document object
        document.body.appendChild(studentDiv);
      }
    }
    // Run code after the document is fully loaded
    window.onload = function() {
      // Create a header element using a document method
      var header = document.createElement('h1');
      header.textContent = 'My College - Student Details';
      document.body.appendChild(header);
      // Create an instance of the Student object
      // Here, marks are 432 out of 500, and the percentage will be rounded
      var student1 = new Student("Arjun", "Computer Science", 432, 500);
      
      // Display the student's details
      student1.displayDetails();
      // Additional information regarding Math usage
      var infoPara = document.createElement('p');
      infoPara.textContent = 'Student details include a randomly generated ID and a rounded percentage computed using Math methods.';
      document.body.appendChild(infoPara);
    }
  </script>
</head>
<body>
</body>
</html>
Explanation
- Random User ID Generation:
 The student ID is generated with:- Math.random()to create a random number.
- Math.floor()to convert it to an integer, then prefixed with “A” (e.g., “A123”).
 
- Rounded Percentage Calculation:
 The percentage is computed as(marks / totalMarks) * 100and then rounded usingMath.round(), ensuring that the displayed percentage is a whole number.

e. Write a program using string object properties and methods.
</>
                        Copy
                        <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My College - Student Details</title>
  <script>
    // User-defined object constructor for Student
    function Student(name, branch, marks, totalMarks) {
      this.name = name;
      // Generate a random user id using Math.random() and Math.floor()
      this.id = "A" + Math.floor(Math.random() * 1000);
      this.branch = branch;
      this.marks = marks;
      this.totalMarks = totalMarks;
      // Calculate percentage and round it to the nearest integer using Math.round()
      this.percentage = Math.round((marks / totalMarks) * 100);
      // Method to display student details using document methods
      this.displayDetails = function() {
        // Create a div element to hold the student details
        var studentDiv = document.createElement('div');
        studentDiv.innerHTML = '<h2>Student Details</h2>' +
                               '<p><strong>Name:</strong> ' + this.name + '</p>' +
                               '<p><strong>ID:</strong> ' + this.id + '</p>' +
                               '<p><strong>Branch:</strong> ' + this.branch + '</p>' +
                               '<p><strong>Marks:</strong> ' + this.marks + ' out of ' + this.totalMarks + '</p>' +
                               '<p><strong>Percentage:</strong> ' + this.percentage + '%</p>';
        // Append the div to the body using the pre-defined document object
        document.body.appendChild(studentDiv);
      }
    }
    // Run code after the document is fully loaded
    window.onload = function() {
      // Create a header element using a document method
      var header = document.createElement('h1');
      header.textContent = 'My College - Student Details';
      document.body.appendChild(header);
      // Create an instance of the Student object
      // Here, marks are 432 out of 500, and the percentage will be rounded
      var student1 = new Student("Arjun Kumar", "Computer Science", 432, 500);
      // Display the student's details
      student1.displayDetails();
      // Additional information regarding String usage
      var infoPara = document.createElement('p');
      infoPara.textContent = 'This example demonstrates string object properties and methods applied to student details.';
      document.body.appendChild(infoPara);
      // --------- String Object Properties and Methods Demonstration ---------
      // Section header for String Operations
      var stringHeader = document.createElement('h2');
      stringHeader.textContent = 'String Object Properties and Methods';
      document.body.appendChild(stringHeader);
      // Using the student name for various string operations
      var nameStr = student1.name; // "Arjun Kumar"
      // Display the length property of the string
      var lengthPara = document.createElement('p');
      lengthPara.textContent = 'Length of student name: ' + nameStr.length;
      document.body.appendChild(lengthPara);
      // Convert the string to uppercase
      var upperPara = document.createElement('p');
      upperPara.textContent = 'Uppercase: ' + nameStr.toUpperCase();
      document.body.appendChild(upperPara);
      // Convert the string to lowercase
      var lowerPara = document.createElement('p');
      lowerPara.textContent = 'Lowercase: ' + nameStr.toLowerCase();
      document.body.appendChild(lowerPara);
      // Extract a substring (first name) using substring() and indexOf()
      var firstName = nameStr.substring(0, nameStr.indexOf(" "));
      var substringPara = document.createElement('p');
      substringPara.textContent = 'First Name (using substring): ' + firstName;
      document.body.appendChild(substringPara);
      // Find the index of the space character in the name using indexOf()
      var indexPara = document.createElement('p');
      indexPara.textContent = 'Index of space in name: ' + nameStr.indexOf(" ");
      document.body.appendChild(indexPara);
      // Split the full name into an array of words using split()
      var splitName = nameStr.split(" ");
      var splitPara = document.createElement('p');
      splitPara.textContent = 'Split name (first and last): ' + splitName.join(" | ");
      document.body.appendChild(splitPara);
      // Display the first character of the name using charAt()
      var charPara = document.createElement('p');
      charPara.textContent = 'First character of the name: ' + nameStr.charAt(0);
      document.body.appendChild(charPara);
    }
  </script>
</head>
<body>
</body>
</html>Explanation
- Student Object Enhancements:
 TheStudentconstructor now includes a randomly generated ID and a rounded percentage calculated with Math methods.
- String Operations Section:
 A new section demonstrates how to use various string properties and methods on the student’s name:- Length: Displays the total number of characters.
- toUpperCase() / toLowerCase(): Converts the name to all uppercase or lowercase letters.
- substring() & indexOf(): Extracts the first name by finding the index of the space character.
- split(): Splits the full name into an array, then joins it back with a custom separator.
- charAt(): Retrieves the first character of the name.
 

f. Write a program using regex object properties and methods.
</>
                        Copy
                        <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My College - Student Details</title>
  <script>
    // User-defined object constructor for Student
    function Student(name, branch) {
      this.name = name;
      // Generate a random user id using Math.random() and Math.floor()
      this.id = "A" + Math.floor(Math.random() * 1000);
      this.branch = branch;
      // Method to display student details using document methods
      this.displayDetails = function() {
        // Create a div element to hold the student details
        var studentDiv = document.createElement('div');
        studentDiv.innerHTML = '<h2>Student Details</h2>' +
                               '<p><strong>Name:</strong> ' + this.name + '</p>' +
                               '<p><strong>ID:</strong> ' + this.id + '</p>' +
                               '<p><strong>Branch:</strong> ' + this.branch + '</p>';
        // Append the div to the body using the document object
        document.body.appendChild(studentDiv);
      }
    }
    // Run code after the document is fully loaded
    window.onload = function() {
      // Create a header element using a document method
      var header = document.createElement('h1');
      header.textContent = 'My College - Student Details';
      document.body.appendChild(header);
      // Create an instance of the Student object (marks and percentage dropped)
      var student1 = new Student("Arjun Kumar", "Computer Science");
      student1.displayDetails();
      // --------- Regex Object Properties and Methods Demonstration ---------
      var regexHeader = document.createElement('h2');
      regexHeader.textContent = 'Regex Object Properties and Methods';
      document.body.appendChild(regexHeader);
      // Define a regular expression to validate that the student's name contains only letters and spaces
      var nameRegex = /^[A-Za-z\s]+$/;
      // Use test() to check if the name matches the regex
      var isNameValid = nameRegex.test(student1.name);
      var testPara = document.createElement('p');
      testPara.textContent = 'Using test(): The student name "' + student1.name + '" is ' + (isNameValid ? 'valid' : 'invalid') + '.';
      document.body.appendChild(testPara);
      // Use match() to extract the first word (first name) from the student name
      var matchResult = student1.name.match(/[A-Z][a-z]+/);
      var matchPara = document.createElement('p');
      matchPara.textContent = 'Using match(): The first word in the name is "' + (matchResult ? matchResult[0] : 'Not Found') + '".';
      document.body.appendChild(matchPara);
      // Use search() to find the index of the first space in the student name
      var searchIndex = student1.name.search(/\s/);
      var searchPara = document.createElement('p');
      searchPara.textContent = 'Using search(): The index of the first space in the name is ' + searchIndex + '.';
      document.body.appendChild(searchPara);
      // Use replace() to remove all spaces from the student name
      var nameWithoutSpaces = student1.name.replace(/\s/g, "");
      var replacePara = document.createElement('p');
      replacePara.textContent = 'Using replace(): The name without spaces is "' + nameWithoutSpaces + '".';
      document.body.appendChild(replacePara);
      // Use exec() to execute a search for a match (similar to test but returns an array)
      var execResult = nameRegex.exec(student1.name);
      var execPara = document.createElement('p');
      execPara.textContent = 'Using exec(): The result is ' + (execResult ? execResult[0] : 'null') + '.';
      document.body.appendChild(execPara);
    }
  </script>
</head>
<body>
</body>
</html>Explanation
- Student Object Update:
 TheStudentconstructor now only accepts the student’s name and branch. A random ID is generated usingMath.random()andMath.floor(). The properties for marks and percentage have been removed.
- Display Method:
 ThedisplayDetails()method creates a div displaying only the student’s name, ID, and branch.
- Regex Section:
 The regex demonstration section works on the student’s name:- test(): Checks if the name contains only letters and spaces.
- match(): Extracts the first word from the name.
- search(): Finds the index of the first space.
- replace(): Removes all spaces from the name.
- exec(): Executes the regex and returns the first match.
 

g. Write a program using date object properties and methods.
</>
                        Copy
                        <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My College - Student Details</title>
  <script>
    // User-defined object constructor for Student
    function Student(name, branch, dob, joinYear) {
      this.name = name;
      // Generate a random user id using Math.random() and Math.floor()
      this.id = "A" + Math.floor(Math.random() * 1000);
      this.branch = branch;
      // Store date of birth (as a Date object) and the year of joining
      this.dob = new Date(dob); // dob should be in a format like "1999-03-15"
      this.joinYear = joinYear;
      // Calculate the age using the Date object
      var today = new Date();
      var age = today.getFullYear() - this.dob.getFullYear();
      var m = today.getMonth() - this.dob.getMonth();
      if (m < 0 || (m === 0 && today.getDate() < this.dob.getDate())) {
          age--;
      }
      this.age = age;
      // Method to display student details using document methods
      this.displayDetails = function() {
        var studentDiv = document.createElement('div');
        studentDiv.innerHTML = '<h2>Student Details</h2>' +
                               '<p><strong>Name:</strong> ' + this.name + '</p>' +
                               '<p><strong>ID:</strong> ' + this.id + '</p>' +
                               '<p><strong>Branch:</strong> ' + this.branch + '</p>' +
                               '<p><strong>Date of Birth:</strong> ' + this.dob.toDateString() + '</p>' +
                               '<p><strong>Age:</strong> ' + this.age + '</p>' +
                               '<p><strong>Year of Joining:</strong> ' + this.joinYear + '</p>';
        document.body.appendChild(studentDiv);
      }
    }
    // Run code after the document is fully loaded
    window.onload = function() {
      // Create a header element using document methods
      var header = document.createElement('h1');
      header.textContent = 'My College - Student Details';
      document.body.appendChild(header);
      // Create an instance of the Student object with a date of birth and year of joining
      var student1 = new Student("Arjun Kumar", "Computer Science", "1999-03-15", 2018);
      student1.displayDetails();
      // --------- Date Object Properties and Methods Demonstration ---------
      var dateHeader = document.createElement('h2');
      dateHeader.textContent = 'Date Object Properties and Methods';
      document.body.appendChild(dateHeader);
      // Create a Date object for the current date and time
      var currentDate = new Date();
      // Display the current date and time using toLocaleString()
      var currentDatePara = document.createElement('p');
      currentDatePara.textContent = 'Current Date and Time: ' + currentDate.toLocaleString();
      document.body.appendChild(currentDatePara);
      // Display individual properties of the current date
      var currentYearPara = document.createElement('p');
      currentYearPara.textContent = 'Current Year: ' + currentDate.getFullYear();
      document.body.appendChild(currentYearPara);
      var currentMonthPara = document.createElement('p');
      // getMonth() returns month index (0-11), add 1 for human-readable format
      currentMonthPara.textContent = 'Current Month: ' + (currentDate.getMonth() + 1);
      document.body.appendChild(currentMonthPara);
      var currentDayPara = document.createElement('p');
      currentDayPara.textContent = 'Current Day: ' + currentDate.getDate();
      document.body.appendChild(currentDayPara);
      var currentHoursPara = document.createElement('p');
      currentHoursPara.textContent = 'Current Hour: ' + currentDate.getHours();
      document.body.appendChild(currentHoursPara);
      var currentMinutesPara = document.createElement('p');
      currentMinutesPara.textContent = 'Current Minutes: ' + currentDate.getMinutes();
      document.body.appendChild(currentMinutesPara);
      var currentSecondsPara = document.createElement('p');
      currentSecondsPara.textContent = 'Current Seconds: ' + currentDate.getSeconds();
      document.body.appendChild(currentSecondsPara);
    }
  </script>
</head>
<body>
</body>
</html>
Explanation
- Student Object Enhancements:
- The constructor now accepts a dobparameter (as a date string) and ajoinYear.
- A Date object is created from the DOB string.
- The student’s age is calculated by comparing the current date with the DOB.
- The displayDetails()method shows the student’s name, randomly generated ID, branch, DOB (formatted withtoDateString()), age, and year of joining.
 
- The constructor now accepts a 
- Date Object Demonstration:
- A Date object representing the current date and time is created.
- Various Date object methods are used:
- toLocaleString()displays the full current date and time.
- getFullYear(),- getMonth(),- getDate(),- getHours(),- getMinutes(), and- getSeconds()extract specific parts of the current date and time.
 
 

h. Write a program to explain user-defined object by using properties, methods, accessors, constructors and display.
</>
                        Copy
                        <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My College - Student Details</title>
  <script>
    // User-defined object constructor for Student
    function Student(firstName, lastName, branch) {
      // Properties
      this.firstName = firstName;
      this.lastName = lastName;
      this.branch = branch;
      // Generate a random user ID using Math.random() and Math.floor()
      this.id = "A" + Math.floor(Math.random() * 1000);
      // Accessor: Define a getter and setter for fullName
      Object.defineProperty(this, 'fullName', {
        get: function() {
          return this.firstName + " " + this.lastName;
        },
        set: function(name) {
          var parts = name.split(" ");
          this.firstName = parts[0];
          this.lastName = parts[1] || "";
        },
        enumerable: true,
        configurable: true
      });
      // Method: Display student details on the page using document methods
      this.displayDetails = function() {
        var studentDiv = document.createElement('div');
        studentDiv.innerHTML = '<h2>Student Details</h2>' +
                               '<p><strong>ID:</strong> ' + this.id + '</p>' +
                               '<p><strong>Full Name:</strong> ' + this.fullName + '</p>' +
                               '<p><strong>Branch:</strong> ' + this.branch + '</p>';
        document.body.appendChild(studentDiv);
      }
    }
    // Run the code after the document is fully loaded
    window.onload = function() {
      // Create an instance of the Student object using the constructor
      var student1 = new Student("Arjun", "Kumar", "Computer Science");
      // Display the student details initially
      student1.displayDetails();
      // Demonstrate the accessor: update the full name using the setter
      var updatePara = document.createElement('p');
      updatePara.textContent = "Updating full name using the accessor...";
      document.body.appendChild(updatePara);
      // Update the fullName property (this will update firstName and lastName)
      student1.fullName = "Rahul Sharma";
      // Display the updated student details
      student1.displayDetails();
    }
  </script>
</head>
<body>
</body>
</html>Explanation
- Properties & Constructor:
 TheStudentconstructor acceptsfirstName,lastName, andbranchas arguments, assigns these values to object properties, and generates a random ID.
- Accessor (Getter and Setter):
 ThefullNameaccessor is defined usingObject.defineProperty(). The getter returns a combination offirstNameandlastName, while the setter splits a new full name into first and last names.
- Method (displayDetails):
 ThedisplayDetails()method creates a div element and uses innerHTML to display the student’s ID, full name, and branch on the webpage.
- Display:
 Initially, the student details are displayed. Then, the full name is updated using the setter, and the updated details are displayed again.

