JavaScript has a number of built-in object types, such as:
Math, Date, Object, Function, Boolean, Symbol, Array, Map, Set, Promise, JSON, etc.
These objects are sometimes referred to as “native objects”.
Constructor functions, commonly referred to as just “constructors”, are special functions that allow us to build instances of these built-in native objects. All the constructors are capitalized.
To use a constructor function, I must prepend it with the operator new.
For example, to create a new instance of the Date object, I can run: new Date(). What I get back is the current datetime, such as:
Thu Feb 03 2022 11:24:08 GMT+0100 (Central European Standard Time)
Besides constructor functions for the built-in objects, I can also define custom constructor functions.
function Icecream(flavor) {
this.flavor = flavor;
this.meltIt = function() {
console.log(`The ${this.flavor} icecream has melted`);
}
}
Now I can make as many icecreams as I want:
function Icecream(flavor) {
this.flavor = flavor;
this.meltIt = function() {
console.log(`The ${this.flavor} icecream has melted`);
}
}
let kiwiIcecream = new Icecream("kiwi");
let appleIcecream = new Icecream("apple");
kiwiIcecream; // --> Icecream {flavor: 'kiwi', meltIt: ƒ}
appleIcecream; // --> Icecream {flavor: 'apple', meltIt: ƒ}
A RegExp object is another built-in object in JavaScript. It’s used to pattern-match strings using what’s known as “Regular Expressions”.
In JavaScript, you can built an instance of the RegExp constructor using new RegExp.
Alternatively, you can use a pattern literal instead of RegExp. Here’s an example of using /d/ as a pattern literal, passed-in as an argument to the match method on a string.
"abcd".match(/d/); // ['d', index: 3, input: 'abcd', groups: undefined]
"abcd".match(/a/); // ['a', index: 0, input: 'abcd', groups: undefined]
Instead of using Array, Function, and RegExp constructors, you should use their array literal, function literal, and pattern literal varieties: [], () {}, and /()/.
However, when building objects of other built-in types, we can use the constructor.
new Date();
new Error();
new Map();
new Promise();
new Set();
new WeakSet();
new WeakMap();
Additional resources
Here is a list of resources that may be helpful as you continue your learning journey.