Back to: JavaScript Tutorial For Beginners and Professionals
Real World Constructors in JavaScript with Examples
In this article, I am going to discuss Real-World Constructors in JavaScript with Examples. Please read our previous article where we discussed Object Instances in JavaScript.
Real World Constructors in JavaScript
JavaScript comes with a set of constructors for instantiating some handy objects—like objects that know how to deal with dates and times, objects that are great at finding patterns in text, and even objects that will give us a new perspective on arrays. Now that we know how constructors work, and also how to use the new keyword, we are in a great position to make use of these constructors, or more importantly the objects they create. Let’s just take a quick dip into a couple, and then we will be all ready to explore them on our own.
Let’s start with JavaScript’s built-in date object. To get one we just use its constructor:
var now = new Date();
This creates a new date representing the current date and time. Calling the Date constructor gives us back an instance of Date that represents the current local date and time. With a date object in hand, we can then use its methods to manipulate dates (and times) and also retrieve various properties of a date and time. Here are a few examples:
var dateString = now.toString();
The above piece of code returns a string that represents the date, like “Thu Feb 04 2021 17:29:29 GMT-0800 (PST)”.
var theYear = now.getFullYear();
Returns the year in the date.
var theDayOfWeek = now.getDay();
Returns a number for the day of the week represented by the date object, like 1 (for Monday).
We can easily create date objects representing any date and time by passing additional arguments to the Date constructor. For instance, say we need a date object representing “May 1, 2021”, we can do that with:
var birthday = new Date(“May 1, 2021”);
We can pass a simple date string to the constructor like this.
And we can get even more specific by including a time:
var birthday = new Date(“May 1, 2021 08:03 pm”);
Now, here we are including a time in the string too. We are just giving you a glimpse of the date object; We will see & check out its full set of properties and methods in the JavaScript: Date Object chapter.
The Array Object in JavaScript
Next up, another interesting built-in object: the array object. While we have been creating arrays using the square bracket notation [1, 2, 3], we can also create arrays using a constructor too:
var emptyArray = new Array();
Creates an empty array with length zero. Here, we are creating a new, empty array object. And at any time, we can add items to it, like this:
emptyArray[0] = 10;
This should look familiar. This is the same way we have always added items to an array. We can also create array objects that have a fixed size. Say we want an array with three items:
var oddNumbers = new Array(3);
oddNumbers[0] = 1;
oddNumbers[1] = 3;
oddNumbers[2] = 5;
We create an array of length three and fill it in with values after we create it. Here we have created an array of length three. Initially, the 3 items in oddNumbers are undefined, but we then set each item in the array to a value. We could easily add more items to the array if we wanted.
None of this should be not so different than what we are used to. Where the array object gets interesting is in its set of methods. We already know about array’s sort method, and here are a few other interesting ones:
oddNumbers.reverse();
This reverses all the values in the array so we have 5, 3, 1 in oddNumbers now. Notice, the method changes the original array.
var aString = oddNumbers.join(” – “);
The join method creates a string from the values in oddNumbers placing a “ – ” between the values and returns that string. So, this returns the string “5 – 3 – 1”.
var areAllOdd = oddNumbers.every(function (x) { return ((x % 2) !== 0); });
Every method takes a function and tests each value of the array to see if the function returns true or false when called on that value. If the function returns true for all the array items, then the result of every method is true.
Again, that’s just the tip of the iceberg, so take a look at JavaScript: The Array Object Chapter to fully explore the array object. We have got all the knowledge we need to take it on.
Two ways to create arrays in JavaScript
Good Point. The bracket notation, [ ], that We have been using to create arrays is actually just a shorthand for using the Array constructor directly. Check out these two similar ways of creating empty arrays:
var items = new Array();
var items = [];
These do the same thing. The bracket notation is supported in the JavaScript language to make our life easier when creating arrays.
Likewise, if we write code like this:
var items = [“a”, “b”, “c”];
We call this array literal syntax. That’s just a short way for using the constructor in another way:
var items = new Array(“a”, “b”, “c”);
If we pass more than one argument, this creates an array holding the values we pass it. And, the objects created from the literal notation or by using the constructor directly are the same, so we can use methods on either one.
We might be thinking about why we would ever use the constructor rather than the literal notation. The constructor comes in handy when we need to create an array of a specific size we determine at runtime, and then add items to it later, like this:
var n = getNumberOfWidgetsFromDatabase(); var widgets = new Array(n); for (var i = 0; i < n; i++) { widgets[i] = getDatabaseRecord(i); };
This code probably uses big arrays that we won’t know the size of until runtime. So, for creating a quick array, using the array literal syntax to create our array objects works wonderfully, but using the Array constructor might make sense when we are creating the array programmatically. We can use either or both as much as we want.
Date and array are not the only built-in objects in JavaScript. There are lots of other objects that come with the language we might find handy at times. Here’s a shortlist, there are more, so we will see them in upcoming respective chapters.
- Object: By using the Object constructor we can create objects. Like arrays, the object literal notation { } is equivalent to using new Object(). That we have seen in the previous chapter.
- Math: This object has properties and methods for doing math operations. Like Math.PI and Math.random().
- RegExp: Use this constructor to create regular expression objects, which allow us to search for patterns even complex ones in the text.
- Error: This constructor creates standard error objects that are handy when catching errors in our code.
Why do constructor names start with a capital letter?
This is a convention that JavaScript developers use so they can easily identify which functions are constructors, and which functions are just regular old functions. Why? Because with constructor functions, we need to use the new operator. In general, using a capital letter for constructors makes them easier to pick out when we’re reading code.
Do the parameter names of a constructor function have to match the property names?
No. We can use whatever names we want for the parameters. The parameters are used to hold values that we want to assign to the object’s properties to customize the object. What matters is the name of the properties we use for the object. That said, we often do use the same names for properties for clarity, so we know which properties we’re assigning by looking at the constructor function definition.
Bit confused by this keyword in the constructor. We’re using this to assign properties to the object, and we’re also using this in the methods of the object. Are these the same thing?
When we call a constructor (to create an object) the value of this is set to the new object that’s being created so all the code that is evaluated in the constructor applies to that new object.
Later, when we call a method on an object, this is set to the object whose method we called. So the this in our methods will always refer to the object whose method was called.
Is it better to create objects with a constructor than with object literals?
Both are useful. A constructor is useful when we want to create lots of objects with the same property names and methods. Using them is convenient, reuses code, and provides consistency across our objects.
But sometimes we just need a quick object, perhaps a one-time-use only object, and literals are short and expressive to use for this. So, it really depends on what our requirements are. Both are great ways to create an object.
How the Date and Array constructor’s work: they seem to support zero or more arguments. Like with Date, if we don’t provide an argument, then we get today’s date, but we can also pass arguments to get other dates. How does that work?
It’s possible to write functions that do different tasks based on the number of arguments. So, if the Array constructor has zero arguments, the constructor knows it is creating an empty array or array with no element; if it has one argument it knows that’s the size of the array, and if it has more arguments, then those arguments are all initial values.
How to check if an object is an instance of a constructor name, but how do we write the code to ask if two objects have the same constructor?
We can check to see if two objects have the same constructor like this:
((fido instanceof Dog) && (spot instanceof Dog))
If this expression results in true, then fido and spot were indeed created by the same constructor.
If we create an object with an object literal, what is it an instance of? Or is it not an instance of anything?
An object literal is an instance of an Object. Think of Object as the constructor for the most generic kind of object in JavaScript. We have already seen this. If we create an object with an object literal, it is an instance of an object, this is how we check
var cadiParams = { make: "GM", model: "Cadillac", year: 1955, color: "tan", passengers: 5, convertible: false, mileage: 12892 }; console.log("cadiParams is an instance of Object: ", cadiParams instanceof Object); //true
In the next article, I am going to discuss Creating JavaScript Object Using Object.create() Method with Examples. Here, in this article, I try to explain Real World Constructors in JavaScript with Examples and I hope you enjoy this Real World Constructors in JavaScript article.