0% found this document useful (0 votes)
30 views

1.8. Usage of JavaScript Objects

The document discusses JavaScript objects including native objects like Number, Boolean, String, Date, Array, Math, and RegExp. It also covers user-defined objects, declaring and accessing properties, methods, and this keyword.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

1.8. Usage of JavaScript Objects

The document discusses JavaScript objects including native objects like Number, Boolean, String, Date, Array, Math, and RegExp. It also covers user-defined objects, declaring and accessing properties, methods, and this keyword.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Learning outcome1:

Use Fundamental Features of

Basic Features

Usage of
Table of Contents
1. Usage of JavaScript Objects ............................................................................................................ 3
1.1. Introduction ............................................................................................................................ 3
1.2. JavaScript Native Objects ........................................................................................................ 3
1.2.1. JavaScript Number Object............................................................................................... 3
1.2.2. JavaScript Boolean Object............................................................................................... 4
1.2.3. JavaScript String Object .................................................................................................. 4
1.2.4. JavaScript Date Object .................................................................................................... 6
1.2.5. JavaScript Array Object ................................................................................................... 7
1.2.6. JavaScript Math Object ................................................................................................... 8
1.2.7. JavaScript RegExp Object ................................................................................................ 9
1.3. User-Defined Objects ............................................................................................................ 10
1.3.1. JavaScript Object Declaration ....................................................................................... 10
1.3.2. JavaScript Object Properties ......................................................................................... 10
1.3.3. JavaScript Nested Objects ............................................................................................. 11
1.3.4. JavaScript Object Methods ........................................................................................... 11
1.3.5. Accessing Object Methods ............................................................................................ 12
1.3.6. Adding a Method to a JavaScript Object....................................................................... 12
1.3.7. JavaScript Object with this Keyword ............................................................................. 13
1.4. with and new in JavaScript Object ........................................................................................ 14
1.4.1. with ............................................................................................................................... 14
1.4.2. new................................................................................................................................ 14
1.5. Exercises ................................................................................................................................ 15
1.6. Homework............................................................................................................................. 20
1. Usage of JavaScript Objects

1.1. Introduction

JavaScript object is a non-primitive data-type that allows you to store multiple collections of data.

Note: If you are familiar with other programming languages, JavaScript objects are a bit different.
You do not need to create classes in order to create objects.

1.2. JavaScript Native Objects

Native JavaScript objects are regular JavaScript objects offered by JavaScript itself. Inbuilt objects,
pre-defined objects, and global objects are other names. No matter the computer or environment,
all users have access to these objects, and they function similarly. Let us describe them below

1.2.1. JavaScript Number Object

The Number object in JavaScript is a built-in global object that represents numerical values. It
provides various methods and properties to perform operations and manipulations on numeric
values.
Creating Number Objects

You can create a Number object using the new keyword and the Number() constructor:

const num1 = new Number(42); // Using constructor


const num2 = Number(3.14); // Without using constructor (same as: const
num2 = 3.14;)

Common Properties of Number Object

Number.MAX_VALUE: Represents the maximum representable numeric value in JavaScript.


Number.MIN_VALUE: Represents the minimum positive representable numeric value in
JavaScript (close to 0).
Number.NaN: Represents "Not-a-Number" value, which indicates an unrepresentable value or
an invalid arithmetic operation.
Number.POSITIVE_INFINITY: Represents positive infinity, which is returned on overflow.
Number.NEGATIVE_INFINITY: Represents negative infinity, which is returned on negative
overflow.

console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324
console.log(Number.NaN); // NaN
console.log(Number.POSITIVE_INFINITY); // Infinity
console.log(Number.NEGATIVE_INFINITY); // -Infinity
Common Methods of Number Object

Number.toFixed(): Formats a number using fixed-point notation with a specified number of


decimal places.
Number.toPrecision(): Formats a number with a specified length, including both integer and
decimal parts.
Number.toString(): Converts a number to a string representation with a specified radix (base).
Number.parseInt(): Parses a string argument and returns an integer.
Number.parseFloat(): Parses a string argument and returns a floating-point number.
Number.isNaN(): Determines whether a value is NaN (Not-a-Number).
Number.isFinite(): Determines whether a value is a finite number.

const num = 3.14159265;

console.log(num.toFixed(2)); // 3.14
console.log(num.toPrecision(4)); // 3.142
console.log(num.toString(16)); // "3.243f6a8885a3"
console.log(Number.parseInt("42")); // 42
console.log(Number.parseFloat("3.14"));// 3.14
console.log(Number.isNaN(NaN)); // true
console.log(Number.isFinite(42)); // true
console.log(Number.isFinite(Infinity));// false

1.2.2. JavaScript Boolean Object

The JavaScript Boolean object is a wrapper class and a member of global objects. Depending on the
value supplied while generating the Boolean object, it is used to produce a Boolean object that
either has a true or false value. When values like 0, -0, an empty text (""), false, null, or Not a
Number (NaN) are provided to the Boolean object when it is being created, the Boolean object
returns false. All other values, including an empty array([]), an empty object(), or the text "false," will
set the initial value for the Boolean object to true in contrast to all these values, which set the initial
value as false for the Boolean object.

Syntax: let bool = new Boolean(val);


The variable bool stores the Boolean value of the "val" parameter, which is converted by the
Boolean object.

1.2.3. JavaScript String Object

The JavaScript string basic data type is wrapped in the String object, which provides a variety of
assistance methods for working with strings of characters. You may call any of the helper methods of
the String object on a string primitive since JavaScript automatically translates between string
primitives and String objects.

Syntax: var val = new String(string);


The "val" variable stores the string value, converted by the string native object in JavaScript.
Method/Property Description Example Output

length Returns the length of the string. "Hello, World!".length 13

"HELLO,
toUpperCase() Converts the string to uppercase. "Hello, World!".toUpperCase()
WORLD!"

toLowerCase() Converts the string to lowercase. "Hello, World!".toLowerCase() "hello, world!"

Returns the index of the first


indexOf(substring) "Hello, World!".indexOf("World") 7
occurrence.

Returns the index of the last


lastIndexOf(substring) "Hello, World!".lastIndexOf("l") 10
occurrence.

replace(search, "Hello, World!".replace("Hello",


Replaces occurrences of a value. "Hi, World!"
replace) "Hi")

Returns a substring based on


substring(start, end) "Hello, World!".substring(0, 5) "Hello"
indices.

slice(start, end) Extracts a section of a string. "Hello, World!".slice(0, 5) "Hello"

Extracts a specified number of


substr(start, length) "Hello, World!".substr(7, 5) "World"
characters.

Removes whitespace from both


trim() " Hello, World! ".trim() "Hello, World!"
ends.

Returns the character at the


charAt(index) "Hello, World!".charAt(7) "W"
specified index.
Returns the Unicode value at the 72 (Unicode for
charCodeAt(index) "Hello, World!".charCodeAt(0)
index. "H")

concat(str1, str2, ...) Concatenates two or more strings. "Hello".concat(", ", "World!") "Hello, World!"

1.2.4. JavaScript Date Object

The JavaScript language includes the Date object as a datatype built-in. The new Date() constructor
creates Date objects. Using various methods, you may perform operations on a Date object after it
has been created. Most methods enable you to access and modify an object's year, month, day,
hour, minute, second, and millisecond properties in either local or UTC (also known as GMT) time.

Syntax: var val = new Date();


The "val" variable stores the current date using the date object
Method/Property Description Example Output
new Date() Creates a new Date object let currentDate = new Date(); Current date and
representing the current date and time
time.
getFullYear() Returns the year (four digits) of the currentDate.getFullYear(); Current year
specified date according to local
time.
getMonth() Returns the month (0-11) for the currentDate.getMonth(); Current month (0-
specified date according to local 11)
time.
getDate() Returns the day of the month (1- currentDate.getDate(); Current day of the
31) for the specified date according month
to local time.
getDay() Returns the day of the week (0-6) currentDate.getDay(); Current day of the
for the specified date according to week (0 = Sunday)
local time.
getHours() Returns the hours (0-23) in the currentDate.getHours(); Current hour
specified date according to local
time.
getMinutes() Returns the minutes (0-59) in the currentDate.getMinutes(); Current minutes
specified date according to local
time.
getSeconds() Returns the seconds (0-59) in the currentDate.getSeconds(); Current seconds
specified date according to local
time.
getMilliseconds() Returns the milliseconds (0-999) in currentDate.getMilliseconds(); Current
the specified date according to local milliseconds
time.
toLocaleDateString() Returns a string representing the currentDate.toLocaleDateString(); Date formatted
date portion of the Date based on based on locale
the locale.
toLocaleTimeString() Returns a string representing the currentDate.toLocaleTimeString(); Time formatted
time portion of the Date based on based on locale
the locale.
toLocaleString() Returns a string representing the currentDate.toLocaleString(); Date and time
Date based on the locale. formatted based
on locale
toDateString() Returns a string representing the currentDate.toDateString(); Human-readable
date portion of the Date in a date
human-readable format.
toTimeString() Returns a string representing the currentDate.toTimeString(); Human-readable
time portion of the Date. time
toString() Returns a string representation of currentDate.toString(); Date and time in a
the Date. standard format
getTime() Returns the numeric value currentDate.getTime(); Numeric value
corresponding to the time for the representing time
specified date according to in ms
universal time.
setFullYear(year) Sets the year (four digits) for the currentDate.setFullYear(2023); Sets the year of the
specified date according to local date
time.
setMonth(month) Sets the month (0-11) for the currentDate.setMonth(11); Sets the month of
specified date according to local the date
time.
setDate(day) Sets the day of the month (1-31) for currentDate.setDate(25); Sets the day of the
the specified date according to local month
time.
setHours(hour) Sets the hours (0-23) for the currentDate.setHours(18); Sets the hours of
specified date according to local the date
time.
setMinutes(minute) Sets the minutes (0-59) for the currentDate.setMinutes(30); Sets the minutes of
specified date according to local the date
time.
setSeconds(second) Sets the seconds (0-59) for the currentDate.setSeconds(45); Sets the seconds of
specified date according to local the date
time.
setMilliseconds(ms) Sets the milliseconds (0-999) for the currentDate.setMilliseconds(500); Sets the
specified date according to local milliseconds of the
time. date

1.2.5. JavaScript Array Object

You may store several values in a single variable using the Array object. A fixed-size sequential
collection of identical-type pieces is kept in it. It is important to conceive of an array as a collection
of variables of the same type, even if it is used to hold data collection.

Syntax: var fruits = new Array( "strawberry", "grape", "peach" );


The array is taken as input and stored in the fruits variable.

Method/Property Description Example Expected


Output
length Returns the number of elements let arr = [1, 2, 3]; console.log(arr.length); 3
in an array.
push(element) Adds one or more elements to let arr = [1, 2, 3]; arr.push(4); [1, 2, 3, 4]
the end of an array. console.log(arr);
pop() Removes the last element from let arr = [1, 2, 3]; arr.pop(); console.log(arr); [1, 2]
an array.
unshift(element) Adds one or more elements to let arr = [2, 3]; arr.unshift(1); [1, 2, 3]
the beginning of an array. console.log(arr);
shift() Removes the first element from let arr = [1, 2, 3]; arr.shift(); [2, 3]
an array. console.log(arr);
indexOf(element) Returns the first index at which a let arr = [1, 2, 3]; 1
specified element is found in the console.log(arr.indexOf(2));
array.
slice(start, end) Returns a shallow copy of a let arr = [1, 2, 3, 4, 5]; [2, 3, 4]
portion of an array. console.log(arr.slice(1, 4));
splice(start, count, Changes the contents of an array let arr = [1, 2, 3, 4, 5]; arr.splice(1, 2, 6, 7); [1, 6, 7, 4, 5]
elements) by removing or replacing existing console.log(arr);
elements and/or adding new
elements.
concat(array) Returns a new array by let arr1 = [1, 2]; let arr2 = [3, 4]; [1, 2, 3, 4]
combining one or more arrays or console.log(arr1.concat(arr2));
values.
join(separator) Joins all elements of an array into let arr = ["apple", "orange", "banana"]; "apple,
a string, separated by the console.log(arr.join(", ")); orange,
specified separator. banana"
forEach(callback) Executes a provided function let arr = [1, 2, 3]; arr.forEach(num => 2, 4, 6
once for each array element. console.log(num * 2));
map(callback) Creates a new array with the let arr = [1, 2, 3]; let doubledArr = [2, 4, 6]
results of calling a provided arr.map(num => num * 2);
function on every element in the console.log(doubledArr);
array.
filter(callback) Creates a new array with all let arr = [1, 2, 3, 4, 5]; let evenArr = [2, 4]
elements that pass the test arr.filter(num => num % 2 === 0);
implemented by the provided console.log(evenArr);
function.

1.2.6. JavaScript Math Object

Using the math object, you may access characteristics and techniques for mathematical constants
and functions. Math is not a constructor, in contrast to other global objects. Math may be used as an
object without being created, and all of its attributes and methods are static and available for use.

Syntax : var pi1 = Math.PI;


The math object stores the value of pi in the pi1 variable.
Method/Property Description Example Expected Output
Math.PI Represents the ratio console.log(Math.PI); 3.14159265358979
of the circumference 3
of a circle to its
diameter
(approximately
3.14159).
Math.abs(x) Returns the absolute console.log(Math.abs(-5)); 5
value of a number.
Math.ceil(x) Rounds a number up console.log(Math.ceil(4.2)); 5
to the nearest integer.
Math.floor(x) Rounds a number console.log(Math.floor(4.9)); 4
down to the nearest
integer.
Math.round(x) Rounds a number to console.log(Math.round(4.5)); 5
the nearest integer.
Math.max(x, y, ...) Returns the largest of console.log(Math.max(2, 8, 5, 1)); 8
zero or more
numbers.
Math.min(x, y, ...) Returns the smallest console.log(Math.min(2, 8, 5, 1)); 1
of zero or more
numbers.
Math.pow(x, y) Returns the result of console.log(Math.pow(2, 3)); 8
raising x to the power
of y.
Math.sqrt(x) Returns the square console.log(Math.sqrt(9)); 3
root of a number.
Math.random() Returns a pseudo- console.log(Math.random()); (Random value
random number between 0 and 1)
between 0 (inclusive)
and 1 (exclusive).
Math.sin(x) Returns the sine of an console.log(Math.sin(Math.PI / 2)); 1
angle (in radians).
Math.cos(x) Returns the cosine of console.log(Math.cos(Math.PI)); -1
an angle (in radians).
Math.tan(x) Returns the tangent of console.log(Math.tan(Math.PI / 4)); 1
an angle (in radians).
Math.log(x) Returns the natural console.log(Math.log(Math.E)); 1
logarithm (base e) of a
number.
Math.exp(x) Returns the result of console.log(Math.exp(1)); 2.71828182845904
raising Euler's number 5
(e) to the power of x.

1.2.7. JavaScript RegExp Object

A character pattern can be described using a regular expression. The JavaScript RegExp class
represents regular expressions. And also both String and RegExp offer methods that apply regular
expressions to text to perform robust pattern matching and search and replace operations.

Syntax: let pattern = /Hi user/i;


The regular expression is specified in this syntax. It is a string containing the regular expression's
pattern.
Method/Property Description Example Expected
Output
test(str) Tests for a match in a let pattern = /hello/; false //case-
string. console.log(pattern.test("Hello, sensitive
World!"));
exec(str) Executes a search for a let pattern = /world/; null
match in a string. console.log(pattern.exec("Hello,
World!"));
source Returns the text of the let pattern = /\d+/; "\d+"
pattern source. console.log(pattern.source);
flags Returns a string let pattern = /abc/gi; "gi" (global
containing the flags of console.log(pattern.flags); and case-
the pattern. insensitive)
test() and exec() with groups Using capturing groups let pattern = /(\d+)-(\d+)/; ["10-20",
in regular expressions. console.log(pattern.exec("10-20")); "10", "20"]
String.prototype.match(regexp) Retrieves the result of let result = "Hello, ["123"] (array
matching a string against 123".match(/\d+/); with match
a regular expression. console.log(result); details)
String.prototype.replace(regexp, Searches a string for a let newString = "Hello, "Hello,
replacement) specified value or a 123".replace(/\d+/, "World"); World"
regular expression, and console.log(newString);
returns a new string
where the specified
values are replaced.
String.prototype.split(regexp) Splits a string into an let parts = ["apple",
array of substrings based "apple,orange,banana".split(/,/); "orange",
on a specified delimiter. console.log(parts); "banana"]

1.3. User-Defined Objects

In JavaScript, you can create custom objects known as user-defined objects. These objects allow you
to define and encapsulate data and behaviour specific to your application. Let us see how to declare
them.

1.3.1. JavaScript Object Declaration

The syntax to declare an object is:

const object_name = {
key1: value1,
key2: value2
}

Here, an object object_name is defined. Each member of an object is a key: value pair separated by
commas and enclosed in curly braces {}.

// object creation
const person = {
name: 'John',
age: 20
};
console.log(typeof person); // object

1.3.2. JavaScript Object Properties

In JavaScript, "key: value" pairs are called properties. You can access the value of a property by
using its key.
Using dot Notation

Here is the syntax of the dot notation. Syntax: objectName.key

const person = { name: 'John', age: 20};

// accessing property
console.log(person.name); // John
Using bracket Notation

Here is the syntax of the bracket notation. Syntax: objectName["propertyName"]

const person = { name: 'John', age: 20, };


// accessing property
console.log(person["name"]); // John

1.3.3. JavaScript Nested Objects

An object can also contain another object. For example,

// nested object
const student = {
name: 'John',
age: 20,
marks: {
science: 70,
math: 75
}
}
// accessing property of student object
console.log(student.marks); // {science: 70, math: 75}

In the above example, an object student contains an object value in the marks property.

1.3.4. JavaScript Object Methods

In JavaScript, an object can also contain a function. For example,

const person = {
name: 'Sam',
age: 30,
// using function as a value
greet: function() { console.log('hello') }
}

person.greet(); // hello
Here, a function is used as a value for the greet key. That's why we need to use person.greet()
instead of person.greet to call the function inside the object. A JavaScript method is a property
containing a function declaration.

1.3.5. Accessing Object Methods

 You can access an object method using a dot notation. The syntax is: objectName.methodKey()
 You can access property by calling an objectName and a key.
 You can access a method by calling an objectName and a key for that method along with ().
For example,

// accessing method and property


const person = {
name: 'John',
greet: function() { console.log('hello'); }
};

// accessing property
person.name; // John

// accessing method
person.greet(); // hello

Here, the greet method is accessed as person.greet() instead of person.greet. If you try to access the
method with only person.greet, it will give you a function definition.
person.greet; // ƒ () { console.log('hello'); }

1.3.6. Adding a Method to a JavaScript Object

You can also add a method in an object. For example,

// creating an object
let student = { };
// adding a property
student.name = 'John';
// adding a method
student.greet = function() {
console.log('hello');
}
// accessing a method
student.greet(); // hello
In the above example, an empty student object is created. Then, the name property is added.
Similarly, the greet method is also added. In this way, you can add a method as well as property to
an object.

1.3.7. JavaScript Object with this Keyword

To access a property of an object from within a method of the same object, you need to use the this
keyword. Let's consider an example.

// creating an object
const person = {
name: 'John',
age: 30,

// accessing name property by using this.name


greet: function() { console.log('The name is' + ' ' + this.name); }
};
person.greet();

In the above example, a person object is created. It contains properties (name and age) and a
method greet.

In the method greet, while accessing a property of an object, this keyword is used. In order to access
the properties of an object, this keyword is used following by . and key.

Note: In JavaScript, this keyword when used with the object's method refers to the object. this is
bound to an object.

However, the function inside of an object can access it's variable in a similar way as a normal
function would. For example,

const person = {
name: 'John',
age: 30,
greet: function() {
let surname = 'Doe';
console.log('The name is' + ' ' + this.name + ' ' + surname); }
};

person.greet();
1.4. with and new in JavaScript Object

1.4.1. with

The with statement was used in older versions of JavaScript to simplify property access for an object.
It allowed you to work with the properties of an object without repeating the object's name.

However, it is considered bad practice and has been deprecated in modern JavaScript due to
potential issues with variable scoping and performance. As a result, it is recommended to avoid
using the with statement.
Example (not recommended, just for illustration):

const person = {
name: 'John',
age: 30
};

// Not recommended to use 'with' statement


with (person) {
console.log(name); // Output: John
console.log(age); // Output: 30
}

1.4.2. new

The new keyword is used to create instances of user-defined constructor functions. When a function
is called with new, it creates a new object, sets this to that new object, and then implicitly returns
the newly created object.

function Person(name, age) {


this.name = name;
this.age = age;
}

const john = new Person('John', 30);


console.log(john.name); // Output: John
console.log(john.age); // Output: 30
1.5. Exercises

Exercises
Write a JavaScript
1. 1 function that takes a person object as input and
returns the
2. person's name and age.
1
function getPersonInfo(person) {
return `${person.name} (${person.age})`;
}
const person = {
name: "John Doe",
age: 25,
address: "123 Main Street, Anytown, CA 12345",
phone: "(555) 555-5555"
};

console.log(getPersonInfo(person)); // John Doe (25)

2 Write a JavaScript function that takes a person object as input and


updates the person's age

function updatePersonAge(person, newAge) {


person.age = newAge;
}

const person = {
name: "John Doe",
age: 25,
address: "123 Main Street, Anytown, CA 12345",
phone: "(555) 555-5555"
};

updatePersonAge(person, 30);
console.log(person.age); // 30

3 Write a JavaScript function that takes a person object as input and


returns a new object with the person's name and address

function getPersonDetails(person) {
return {
name: person.name,
address: person.address
};
}

const person = {
name: "John Doe",
age: 25,
address: "123 Main Street, Anytown, CA 12345",
phone: "(555) 555-5555"
};

const personDetails = getPersonDetails(person);

console.log(personDetails);
// { name: "John Doe", address: "123 Main Street, Anytown, CA 12345" }

4 Write a JavaScript function that takes an array of person objects as


input and returns a new array with the people who are over the age of
18.

function getPeopleOver18(people) {
const over18 = [];
for (const person of people) {
if (person.age >= 18) {
over18.push(person);
}
}
return over18;
}

const people = [
{ name: "John Doe", age: 25 },
{ name: "Jane Doe", age: 17 },
{ name: "Peter Smith", age: 30 }
];

const over18People = getPeopleOver18(people);

console.log(over18People); // [ { name: "John Doe", age: 25 }, {


name: "Peter Smith", age: 30 } ]

5 Write a JavaScript function to add a new property to the book object.


The new property should be called "isbn" and its value should be
"0345391802".

function addISBNToBook(book) {
book.isbn = "0345391802";
}
// Example usage:
const myBook = {
title: "Sample Book",
author: "John Doe",
year: 2023,
};
console.log(myBook);// before adding isbn property
addISBNToBook(myBook);
console.log(myBook);// after adding isbn property

Write a JavaScript function to delete the "genre" property from the


6 book object.
function deleteGenreFromBook(book) {
delete book.genre;
}

deleteGenreFromBook(book);

Write a JavaScript function to check if the book object has the "isbn"
7 property.
function hasIsbnProperty(book) {
return book.hasOwnProperty("isbn");
}

console.log(hasIsbnProperty(book)); // true

Write a JavaScript function to get the value of the "isbn" property


8 from the book object.

function getIsbnFromBook(book) {
return book.isbn;
}

console.log(getIsbnFromBook(book)); // "0345391802"

Write a JavaScript function to sort the properties of the book object


9 alphabetically.
function sortBookProperties(book) {
const properties = Object.keys(book);
properties.sort();

for (const property of properties) {


console.log(property + ": " + book[property]);
}
}

sortBookProperties(book);
Write a JavaScript function to check if two book objects are equal.
10
function areBookObjectsEqual(book1, book2) {
if (Object.keys(book1) !== Object.keys(book2)) {
return false;
}

for (const property in book1) {


if (book1[property] !== book2[property]) {
return false;
}
}

return true;
}

console.log(areBookObjectsEqual(book, newBook)); // true

Write a JavaScript function to convert a book object to a string.


function bookObjectToString(book) {
11 const properties = Object.keys(book);
const propertyStrings = properties.map((property) => property + ": " + book[property]);

return propertyStrings.join(", ");


}

console.log(bookObjectToString(book)); // "title: The Hitchhiker's Guide to the Galaxy,


author: Douglas Adams, genre: Science fiction, numberOfPages: 224, isbn: 0345391802"

Write a function that takes an object representing a product as input


12 and returns the product's price per unit.
const product = {
name: "Widget",
price: 150,
quantity: 5
};

function calculatePricePerUnit(product) {
if (!product || typeof product !== "object" || !("price" in product) || !("quantity" in
product)) {
throw new Error("Invalid product input");
}

if (typeof product.price !== "number" || typeof product.quantity !== "number" ||


product.price <= 0 || product.quantity <= 0) {
throw new Error("Invalid price or quantity value");
}

return product.price / product.quantity;


}

const pricePerUnit = calculatePricePerUnit(product);


console.log(pricePerUnit);

13 Write a function that takes an array of objects representing different


students as input and returns every student's average grade.

const students = [
{
name: "John",
grades: [85, 90, 78, 95]
},
{
name: "Jane",
grades: [90, 92, 88, 87]
},
{
name: "Alice",
grades: [78, 82, 79, 88]
}
];

function calculateAverageGrades(students) {
const result = [];

for (const student of students) {


const grades = student.grades;
const averageGrade = grades.reduce((sum, grade) => sum + grade,
0) / grades.length;
result.push({ name: student.name, averageGrade });
}

return result;
}
const averageGrades = calculateAverageGrades(students);
console.log(averageGrades);
1.6. Homework

1. Write a function that takes an object representing a customer as input and returns the
customer's total spending.
2. Create an object to represent a shopping cart. The object should have the following
properties:
 items in cart
 total price
3. Write a function that takes an object representing a shopping cart as input and returns
the number of items in the cart.
4. Create an object to represent a checkout process. The object should have the following
properties:
 items in checkout
 total price
 shipping address
 payment information

5. Write a function that takes an object representing a checkout process as input and
returns the shipping cost.
6. Create an object to represent a shipping label. The object should have the following
properties:
 recipient name
 recipient address
 recipient phone number
 shipping carrier
 tracking number

7. Write a function that takes an object representing a shipping label as input and returns
the shipping label as a string.
8. Create an object to represent a receipt. The object should have the following properties:
 items purchased
 total price
 shipping cost
 tax
 grand total

9. Write a function that takes an object representing a receipt as input and returns the
receipt as a string.

You might also like