In our starter files, open the index.html page from this lessons folder:
07.Objects-In-More-Depth > 01.The-object-constructor
Pretty much anything we can think of that has certain properties can be a good use for an object in JavaScript.
For example, a person can be an object, and the properties could be the name, age, height, and any other piece of information which we can give to a person
A computer could be an object too, with properties such as the brand, model, CPU speed, year of manufacture and the memory. When we think of objects like this, there use cases are huge.
As with arrays, there are different ways to construct an object. The style we have looked at previously is the object literal, and it is used to create and define a new object using the curly braces to contain the properties.
Another way is to use a constructor and we have used constructors before with Arrays. We set up arrays either literally like this:
const pizza = ['dough', 'pepperoni'];
Or we used the new Array constructor:
const ingredients = new Array();
ingredients.push('cheese');
The same goes for objects too.
The starter file has an object literal:
// Object literal
let user = {
first: 'Chris',
last: 'Dixon',
occupation: 'web developer',
loggedIn: true,
foods: ['pizza', 'mexican', 'indian'],
};
We can comment this example out, and then recreate it with the Object constructor. This will create an object wrapper for us to add properties too:
let user = new Object();
user.first = 'Chris';
user.last = 'Dixon';
user.occupation = 'web developer';
user.loggedIn = true;
user.foods = ['pizza', 'mexican', 'indian'];
console.log(user);
Similar to the above array example, we begin with the new
keyword to create an object. This is stores into a variable called user
which we add new properties to.
We can also access single properties in the same way as previously used, using the dot notation:
console.log(user.first); // Chris
Or by using the bracket notation:
console.log(user['first']); // Chris
Both giving the same result.
And accessing the property like this also allows us to update the value:
user.first = 'Christopher';
console.log(user['first']); // Christopher
As a side note, if we accidentally had more than one property with the same name, since ES2015, the value of last occurrence will be used, rather than throwing an error.
To remove a property, we can use JavaScript’s delete
operator:
delete user.first;
console.log(user['first']); // undefined
This is two ways to create an object in JavaScript. Both are valid, but how you use them is down to personal preference.