Javascript Objects
Defining JavaScript Objects
Generally, JavaScript is known as an Object Oriented Programming language. Hence, in JavaScript, objects are the most important data types and forms. They are entirely different from primitive data types in JavaScript. As it was mentioned in the chapter “Datatypes”, there are seven data types in JavaScript, six of which are called “primitive” as their values include a single thing ( it can be a number, a string, etc.).
Unlike data types, we use objects for storing keyed collections of different data and more complicated entities. In JavaScript, objects are included in all aspects of the language, so you need to learn them as soon as you start to study the language.
Objects are created with figure brackets {…} and should have a list of properties. Property is known as a “key: value”, in which key or property name is a string and value can be whatever.
You can create an empty object running one of the following syntaxes:
let user = new Object(); // "object constructor" syntax
let user = {}; // "object literal" syntax
As a rule, figure brackets {…} are used. This declaration is called the object literal.
Properties and Literals
You can instantly input properties in that brackets as pairs of “key: value”, like this:
let site = { // an object
name: "W3Docs", // by key "name" store value "Web"
};
the site has one property: the name "name" and the value "Web".
Property values can be accessed using dot notation, as follows:
let site = { // an object
name: "Web", // by key "name" store value "Web"
};
// get property values of the object:
console.log(site.name); // Web
It can have any type of value. For example:
site.haveAdmin = true;
delete operator is used for deleting a property. For instance:
delete site.name;
Multiword property names can also be used. But they need to be quoted like this:
let user = {
site: "Web",
"teaches JS": true // multiword property name must be quoted
};
End the last property of the list with a comma:
let site = {
name: "Web",
haveAdmin: true,
}
Square Brackets
The dot access doesn’t operate for multiword properties. Here is an example:
// this would give a syntax error
site.teaches JS = true
The dot needs the key for being a valid variable identifier. It means no limitations, such as spaces, etc.
You can use an alternative square bracket notation. It will operate with any string. For instance:
let site = {};
// set
site["teaches JS"] = true;
// get
console.log(site["teaches JS"]); // true
// delete
delete site["teaches JS"];
console.log(site);
With the help of the square brackets, you can keep the property name as a result of any expression like this:
let key = "teaches JS";
// same as site["teaches JS"] = true;
site[key] = true;
In this case, the variable key can either be measured at run time or lean on the user input. Then you can use it for accessing the property as follows:
let site = {
name: "Web",
};
let key = prompt("What do you want to know about the site?", "name");
console.log(site[key]); // If enter "name", you will see Web
Note that you can’t use the dot notation similarly:
let site = {
name: "Web"
};
let key = "name";
console.log(site.key) // undefined
Computed Properties
Square brackets are also used in an object literal. It is known as computed properties.
Here is an example:
let car = prompt("Which car do you like?", "bmw");
let color = {
[car]: "white", // the property's name is taken from the variable car
};
console.log(color.bmw); // white, if car="bmw"
You can also use more complicated expressions in square brackets, like this:
let car = 'bmw';
let carColor = {
[car + 'Color']: 'white' // carColor.bmwColor = 'white'
};
console.log(carColor.bmwColor); // white
So, when the name of the property is simple and known, you can use dots. And when you need something more complicated, then turn to square brackets.
Shorthand for Property Value
In real code, existing variables are often used as property name values.
Here is an example:
function makeCar(name, model) {
return {
name: name,
model: model,
// ...other properties
};
}
let car = makeCar("BMW", "M5");
console.log(car.name); // BMW
function makeCar(name, model) {
return {
name, // same as name: name
model // same as model: model
// ...
};
}
Both normal properties and shorthands can be used in the framework of the same project. It will look like this:
let car = {
name, // same as name:name
model: "M5"
};
The “for...in” loop
The “for...in” loop is a unique form of a loop. It’s totally different from the for(;;).
The syntax is the following:
for (key in object) {
// executes the body for each key among object properties
}
Let’s have a look at an example, where all properties of the car are output:
let car = {
name: "Mercedes",
model: "C-Class Cabriolet",
toDrive: true
};
for (let key in car) {
// keys
console.log(key); // name, model, toDrive
// values for the keys
console.log(car[key]); // Mercedes, C-Class Cabriolet, true
}
Take into account that all the constructs of “for” gives an opportunity to declare the looping variable in the loop. For example, let key in the example given above. Another variable name can also be used instead of the key.
Checking Existence
One of the most significant advantages of objects is that it gives access to any property. No error will occur, in case the property doesn’t exist. If you access a non-existing property, you will be returned to undefined. It gives a unique opportunity of checking the property exists or not:
let car = {};
console.log(car.noSuchProperty === undefined); // true means "no such property"
You can use a unique operator "in" as well for checking a property existence. To run it, use the following syntax:
"key" in object
Copy by Reference
One of the principal differences objects via primitives is that they can be stored and copied by reference.
You can assign/copy primitive values (strings, numbers, booleans) as an entire value. Just look at this example:
let message = "Welcome to W3Docs!";
let phrase = message;
In consequence, you will have two independent variables; each of them will store the string “Welcome to W3Docs!”.
Objects don’t work like that.
A variable will store not the object but its “address in memory”. In other words, it stores just a reference to it.
For instance:
let car = {
name: "BMW"
};
Where the object is in the memory, and the variable car contains a reference to it. Anytime you copy an object variable, you duplicate the reference, but the object is not copied.
For example:
let car = {
name: "BMW"
};
let sportCar = car; // copy the reference
Comparing by Reference
In JavaScript, two objects can be considered equal only in case they are the same object.
For example, two variables are equal when they reference the same object:
let obj1 = {};
let obj2 = obj1; // copy the reference
console.log(obj1 == obj2); // true, both variables reference the same object
console.log(obj1 === obj2); // true
In the following case, the two independent objects can’t be considered equal, even though both of them are empty:
let obj1 = {};
let obj2 = {}; // two independent objects
console.log(obj1 == obj2); // false
Const object
An object that is proclaimed const can be changed. Here is an example:
const car = {
name: "BMW"
};
car.model = "M5"; // (*)
console.log(car.model); // M5
You may think that the (*) will give an error, but there is no error here. You will wonder why. The reason is that const can fix only the value of the car. It will cause an error only while trying to set a car to something else like this:
const car = {
name: "BMW"
};
// Error (can't reassign car)
car = {
name: "Mercedes"
};
console.log(car);
Clone and Merge, Object.assign
To copy an object variable means to create another reference to the same object.
But what to do when you need to duplicate the object?
Of course, you can clone it, but it is not an easy job, as JavaScript doesn’t have a built-in method. So, whenever you need to do so, create a new object replicating its structure and iterating over the properties and copy them on the primitive level. The example is as follows:
let car = {
name: "BMW",
model: "M5"
};
let cloneObj = {}; // the new empty object
// start copying all properties of the car into it
for (let key in car) {
cloneObj[key] = car[key];
}
// now clone is a fully independent clone
cloneObj.name = "BMW"; // changed the data in it
console.log(car.name); // still BMW in the original object
The Object.assign method is used for that, as well. You just need to use the following syntax:
Object.assign(dest, [src1, src2, src3...])
It can also be used for merging several objects:
let car = {
name: "BMW"
};
let resolve1 = {
canDrive: true
};
let resolve2 = {
canChange: true
};
// duplicates overall properties from resolve 1 and resolve2 into car
Object.assign(car, resolve1, resolve2); // now car = { name: "BMW", canDrive: true, canChange: true }
console.log(car);
In JavaScript, objects are much more powerful than it can seem from the first sight. This is an extensive topic, and you will learn more about it in the next chapters.
0 Comments
CAN FEEDBACK
Emoji