0% found this document useful (0 votes)
6 views7 pages

JavaScript Object Creation Exercises

This document contains 9 exercises on working with JavaScript objects and dates. It demonstrates how to create objects, add properties and methods to objects, sort and display arrays of data, and perform date calculations. Key concepts covered include creating objects with the new keyword, accessing object properties with dot notation, defining methods, getting and setting date values, and using setInterval to continuously update elements on a page.

Uploaded by

Asad Akhlaq
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views7 pages

JavaScript Object Creation Exercises

This document contains 9 exercises on working with JavaScript objects and dates. It demonstrates how to create objects, add properties and methods to objects, sort and display arrays of data, and perform date calculations. Key concepts covered include creating objects with the new keyword, accessing object properties with dot notation, defining methods, getting and setting date values, and using setInterval to continuously update elements on a page.

Uploaded by

Asad Akhlaq
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

LAB 8 JavaScript – Objects

JavaScript – Objects
The syntax for adding a property to an object is –

[Link] = propertyValue;

For example − The following code gets the document title using the "title" property of the
document object.
var str = [Link];

Language − This attribute specifies what scripting language you are using. Typically, its value
will be JavaScript. Although recent versions of HTML (and XHTML, its successor) have phased
out the use of this attribute.

Object Methods
Methods are the functions that let the object do something or let something be done to it.

For example − Following is a simple example to show how to use the write() method of
document object to write any content on the document. [Link]("This is test");

Exercise 1.
Try the following example; it demonstrates how to create an Object.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object
[Link] = "Perl"; // Assign properties to the object
[Link] = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
[Link]("Book name is : " + [Link] + "<br>");
[Link]("Book author is : " + [Link] + "<br>");
</script>
Output
</body> Book name is : Perl
</html> Book author is : Mohtashim
Exercise 2.
This example demonstrates how to create an object with a User-Defined Function. Here this
keyword is used to refer to the object that has been passed to a function.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
[Link] = title;
[Link] = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
[Link]("Book title is : " + [Link] + "<br>");
[Link]("Book author is : " + [Link] + "<br>");
</script>
Output
</body> Book title is : Perl
</html> Book author is : Mohtashim

Exercise 3. User-defined objects


Try the following example; it shows how to add a function along with an object.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
[Link] = amount;
}
function book(title, author){
[Link] = title;
[Link] = author;
[Link] = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
[Link](100);
[Link]("Book title is : " + [Link] + "<br>");
[Link]("Book author is : " + [Link] + "<br>");
[Link]("Book price is : " + [Link] + "<br>");
</script> Output
</body> Book title is : Perl
</html> Book author is : Mohtashim
Book price is : 100

Exercise [Link] to get time


<html>
<script type="text/javascript">
function Time()
{
var currentTime=new Date()
var hours=[Link]()
var minutes=[Link]()
var seconds=[Link]()
[Link]("<b>" + hours+ "hours" + minutes + "minutes" + seconds + "seconds </b>")
}
</script>
<body onload="Time()">
</body>
</html>
Exercise 5. Write a function that takes as parameters the times table required and the values at
which it should start and end. For example, you might try the two times table displayed starting
with 2 * 1 and ending at 2 * 10.
<!DOCTYPE html>
<html lang="en">
<head>
<title> Exercise 5. </title>
</head>
<body>
<script>
function writeTimesTable(timesTable, timesByStart, timesByEnd) {
for (; timesByStart <= timesByEnd; timesByStart++) {
[Link](timesTable + " * " + timesByStart + " = " +
timesByStart * timesTable + "<br />");
OUTPUT
} 2*1=2
} 2*2=4
2*3=6
writeTimesTable(2, 1, 10); 2*4=8
</script> 2 * 5 = 10
2 * 6 = 12
</body> 2 * 7 = 14
</html> 2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

Exercise 6. Obtain a list of names from the user, storing each name entered in an array. Keep
getting another name until the user enters nothing. Sort the names in ascending order and then
write them out to the page, with each name on its own line.

<!DOCTYPE html>
<html lang="en">
<head>
<title> Exercise 6.</title>
</head>
<body>
<script>
var inputName = "";
var namesArray = [];
while ((inputName = prompt("Enter a name", "")) != "") {
namesArray[[Link]] = inputName;
}
[Link]();
var namesList = [Link]("<br/>");
[Link](namesList);
</script>
</body>
</html>
Exercise [Link] a page that gets the user’s date of birth. Then, using that information, tell her
on what day of the week she was born.

<!DOCTYPE html>
<html lang="en">
<head>
<title> Exercise 7</title>
</head>
<body>
<script>
var days = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"];
var year = prompt("Enter the four digit year you were born.");
var month = prompt("Enter your birth month (1 - 12).");
var date = prompt("Enter the day you were born.");
var birthDate = new Date(year, month - 1, date);
alert(days[[Link]()]);
</script>
</body>
</html>
Exercise 8. Create a web page display current time in hour, minutes, and seconds.

<!DOCTYPE html>
<html lang="en">
<head>
<title> Exercise 8. </title>
</head>
<body>
<div id="output"></div>
<script>
function updateTime() {
var date = new Date();
var value = [Link]() + ":" +
[Link]() + ":" +
[Link]();
Output:
[Link]("output").innerHTML = value; Current Time
}
setInterval(updateTime, 1000);
</script>
</body>
</html>
Exercise 9. Using the Date type, calculate the date 12 months from now and write this into a
web page.
<!DOCTYPE html>
<html lang="en">
<head>
<title> Exercise 9. </title>
</head>
<body>
<script>
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var nowDate = new Date();
[Link]([Link]() + 12);
[Link]("Date 12 months ahead is " + [Link]());
[Link](" " + months[[Link]()]);
[Link](" " + [Link]());
</script>
</body>
</html> Check out Put

Common questions

Powered by AI

Sorting an array of strings is useful in scenarios where ordered representation of data is critical, such as maintaining list alphabets, preparing reports, or improving search operations. In JavaScript, the 'sort()' method organizes array elements lexicographically by default, which suits string arrays well. For user-entered names, the prompt-collect-store pattern shown in demonstrates how an array of names can be sorted to ensure alphabetical order, enhancing readability and data management within applications.

The 'this' keyword in JavaScript is significant because it allows methods to reference and manipulate the properties of the current instance of the object they are called on. This is crucial in scenarios where properties need to be accessed or modified in response to method calls, ensuring that the method's operations are applied to the specific object instance. In , 'this.price = amount' within the 'addPrice' method demonstrates how 'this' is used to set a property on a specific instance of the object methodically.

JavaScript can handle and store user input dynamically in arrays by using loops that continue to prompt the user until a certain condition is met, such as entering an empty string. During this process, valid inputs are stored in an array. This is illustrated in where a 'while' loop continues to collect non-empty input from 'prompt()', appending each entry into 'namesArray'. The method 'namesArray.sort()' can then be used to organize this data, demonstrating efficient input handling for dynamic datasets.

When creating an object using a user-defined function in JavaScript, a function acts as a constructor and the 'this' keyword is used to assign properties and methods to the new object. This approach allows for a more structured and reusable object creation pattern. In contrast, directly instantiating a plain object involves manually defining properties using 'objectName.propertyName = value' syntax, which is more straightforward but less scalable for multiple instances. The user-defined function approach is demonstrated by defining a 'book' function and assigning a method like 'addPrice' to the object in .

JavaScript can display real-time updates of the current time on a webpage using the 'setInterval()' function, which repeatedly calls a specified function at designated intervals, allowing continuous updates. This is exemplified in where 'setInterval(updateTime, 1000)' invokes the 'updateTime' function every second to refresh and display the current time in the format 'hours:minutes:seconds' using 'new Date()'. This approach is efficient for creating dynamic time displays that require constant refreshes.

When calculating future dates using JavaScript, it's crucial to handle date boundaries such as month-end overflows, leap years, and varying month lengths. Using built-in Date methods like 'setMonth()' properly manages these boundary conditions. For instance, in , 'nowDate.setMonth(nowDate.getMonth() + 12)' calculates the date 12 months ahead correctly by internally adjusting for overflow. It’s essential to test date manipulations under scenarios like February in leap years to ensure robust handling of all edge cases.

JavaScript manages output operations through the document object's methods such as 'document.write()'. These methods allow dynamic content insertion directly into a webpage's DOM, often used for displaying immediate outputs or illustrating learning concepts. For example, 'document.write("This is test")' writes text to the document as shown in . However, these methods are less commonly used in modern JavaScript development, where DOM manipulation via the HTMLElement interface and JavaScript frameworks provides more control and best practices.

To determine the day of the week a user was born in JavaScript, prompt inputs for year, month, and date can be used to instantiate a 'Date' object with the user's birth date. The 'getDay()' method of the Date object returns an integer corresponding to the day of the week (0 for Sunday, 6 for Saturday). This integer can be used to index an array of weekday names to output the specific day. As shown in , the days array maps integers to weekday names, allowing the script to alert the user of their birth day efficiently.

'document.write()' offers simple and direct syntax for writing content to a page, which can be advantageous for quick demonstrations or learning exercises, as shown in . However, its disadvantages in modern web development are significant: it can overwrite the entire DOM if used after the page has loaded, leading to loss of content and functionality. It also blocks browser rendering, lowering performance and violating progressive enhancement principles, making it unsuitable for dynamic applications. Modern approaches prefer DOM manipulation via JavaScript using 'createElement', 'appendChild', or libraries like React and Angular for better performance and maintainability.

Creating interactive mathematical functions like times tables in JavaScript enhances educational tools and learning by providing instant feedback and dynamic content presentation that mirrors classroom interactions. As seen in , functions can prompt users to input specific parameters, execute calculations dynamically, and display results in real-time. This immediate interaction helps reinforce learning concepts, making JavaScript a powerful ally in educational applications by offering hands-on, experiential learning that deepens understanding and retention.

You might also like