1.8. Usage of JavaScript Objects
1.8. Usage of JavaScript Objects
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.
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
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:
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
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
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.
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.
"HELLO,
toUpperCase() Converts the string to uppercase. "Hello, World!".toUpperCase()
WORLD!"
concat(str1, str2, ...) Concatenates two or more strings. "Hello".concat(", ", "World!") "Hello, World!"
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.
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.
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.
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.
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.
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
In JavaScript, "key: value" pairs are called properties. You can access the value of a property by
using its key.
Using dot Notation
// accessing property
console.log(person.name); // John
Using bracket Notation
// 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.
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.
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 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'); }
// 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.
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,
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
};
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.
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"
};
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
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"
};
console.log(personDetails);
// { name: "John Doe", address: "123 Main Street, Anytown, CA 12345" }
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 }
];
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
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
function getIsbnFromBook(book) {
return book.isbn;
}
console.log(getIsbnFromBook(book)); // "0345391802"
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;
}
return true;
}
function calculatePricePerUnit(product) {
if (!product || typeof product !== "object" || !("price" in product) || !("quantity" in
product)) {
throw new Error("Invalid product input");
}
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 = [];
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.