18.5 Other Global Objects
Predefined objects are the native objects that JavaScript provides as part of the language. These ready-made objects provided by JavaScript include Array, Boolean, Date, Function, Map, Set, Math, Number, RegExp, String, and Object. You already got to know some of them in the previous sections. In the following sections, I’ll briefly describe the objects of JavaScript that haven’t been mentioned yet.
18.5.1 The Top Object “Object”
This is the object from which all other objects in JavaScript are derived. Every object in JavaScript is of the Object type in any case and may belong to more specific types (e.g., String) as well. The Object object provides properties and methods that are available for all other objects to work with. Basically, an object of the Object type is just a container for data such as strings or numbers, but you can also place function objects into it. You can create an object in the long notation using new Object as follows:
let data = new Object();
data.name = "John Doe";
data.account number = 34234123;
data.aba = 7200032123;
Or you can just write it as usual as an object literal:
let data = {
name: "John Doe",
Account number: 34234123,
ABA: 7200032123
};
18.5.2 Objects for the Primitive Data Types: Number, String, and Boolean
You’ve already used the primitive data types for numbers, strings, and truth values regularly in this book. Example:
let iVal = 1234;
console.log(typeof iVal); // Output: number
let str = "string";
console.log(typeof str); // Output: string
let bool = false;
console.log(typeof bool); // Output: Boolean
In JavaScript, there are also full-fledged object versions for the primitive data types, for which appropriate methods are provided for the type. Here’s an example with the object versions for the primitive data types:
let iOVal = new Number(1234);
console.log(typeof iOVal); // Output: object
let oStr = new String("String");
console.log(typeof oStr); // Output: object
let oBool = new Boolean(false);
console.log(typeof oBool); // Output: object
In practice, however, it’s recommended not to use the object version of the primitive data types, but to leave it at the primitive form. The object version only makes the code more complicated and slows down the execution speed of the script. Things get more complicated when you compare a variable with the primitive data type and an object version. For example:
let iVal = 1234;
let iOVal = new Number(1234);
if ( iVal == iOVal) {
console.log("The value of iVal is equal to iOVal.");
}
else {
console.log("The value of iVal is not equal to iOVal.");
}
if ( iVal === iOVal ) {
console.log("The value and type of iVal is equal to iOVal.");
}
else {
console.log("The value and type of iVal is not equal to iOVal.");
}
Listing 18.23 /examples/chapter018/18_5_2/script.js
When comparing with the == operator, true gets returned because JavaScript performs an automatic conversion here. A comparison with the === operator, on the other hand, returns false because the value is the same, but the type is different. In practice, it’s recommended to use the === operator in JavaScript for a direct comparison because, in most cases, you don’t want to have automatic type conversion. Usually, you want to have a strict comparison of two values, taking type and value into account.
If you want to use the methods of String, Number, or Boolean objects that are provided, you don’t need to create a String, Number, or Boolean object manually via String(), Number(), or Boolean() because as soon as you call a method with the primitive data types, the primitive data type will get converted into a corresponding object. For example:
let str = "string";
console.log("Number of characters: " + str.length); // 12
console.log(str.toUpperCase()); // CHARACTER STRING
let iVal = 1234;
console.log("1234 as dual number : " + iVal.toString(2)); // 10011010010
console.log("1234 as hexadecimal number : " + iVal.toString(16)); // 4d2
console.log("1234 as octal number : " + iVal.toString(8)); // 2322
Due to the automatic type conversion, JavaScript converts the primitive data types into a transient object here. The str variable temporarily becomes a String object, and iVal temporarily becomes a Number object when the corresponding methods for String and Number objects are called, respectively.
18.5.3 “Function” Object
I’ve already mentioned that functions in JavaScript are also objects. All functions in JavaScript are based on Function. By using the Function object, you can access useful properties and some methods. In practice, you could theoretically also create a function using the constructor function via new Function(), but this form is relatively rarely used and needed.
18.5.4 “Date” Object
The Date object provides you with an extensive set of methods for different calculations of date and time. To use the Date object, you need to create a new object via the constructor function, new Date(). Internally, JavaScript uses the milliseconds that have elapsed since January 1, 1970, at 00:00:00 as the unit. Let’s take a look at a simple example:
let date = new Date();
console.log(date); // 2023-02-25T17:01:17.952Z
console.log(Date.parse(date)); // ms since 1/1/1970; 00:00
Note that the system time refers to the time at the user whose web browser or general runtime environment is running the script. The current system time of the server computer isn’t determined here.
18.5.5 “Math” Object
For various types of calculations, the Math object is available with useful features and methods. In practice, you don’t need to create a Math object via the constructor function new Math(), but you can use the features and methods directly via Math.Property or Math.Method(). Take a look at this example.
console.log("Constant for Pi : " + Math.PI); // 3.141592653589793
let r = 12;
let a = r * r * Math.PI; // calculate circular area
console.log(a);
console.log(Math.random()); // generate pseudo-random number between 0 and 1
18.5.6 “Map” Object
Map allows you to create ordered lists from key-value pairs. Such a map is often referred to as an associative array. In this context, the keys and the values can consist of any data type. There are many useful methods available to use the entries. The following example demonstrates a map using zip codes:
let zip = new Map([
[97217, "Portland"],
[60647, "Chicago"],
[02114, "Boston"],
[77007, "Houston"]
]);
let zipTmp = zip.get(97217);
console.log(zipTmp); // Output: Portland
// Add key-value pair
zip.set(94112, "San Francisco");
Listing 18.24 /examples/chapter018/18_5_6/script.js
18.5.7 “Set” Object
A Set object is a collection of values of any type that are stored in the order in which they are added. The highlight is that each value is unique in a Set. An algorithm internally checks for equality before adding. You can add individual elements using add(). If you use has(), you can check if an element already exists in the set. You can determine the number of elements via size(). For this purpose, here’s a simple example with the different methods related to Set:
let mySet = new Set([1, 3, 5]);
mySet.add(7); // Added at the end
mySet.add(3); // Will not be added, already exists
mySet.add("some text"); // Add to the end
// Check
console.log(mySet.has(5)); // = true
console.log(mySet.has(9)); // = false
console.log(mySet.size); // = 5
// Iterate through a Set and output
for (let item of mySet) console.log(item);
// Delete element
mySet.delete(3);
mySet.delete("some text");
Listing 18.25 /examples/chapter018/18_5_7/script.js