Objects in JavaScript are collections of key/value
pairs. The values can consist of properties and methods, and may contain all other JavaScript data types, such as strings, numbers, and Booleans.
So roughly:
- all objects in JavaScript are maps (dictionaries) from strings to values.
- A (key, value) entry in an object is called a property.
- The key of a property is always a text string.
- The value of a property can be any JavaScript value, including a function.
- Methods are properties whose values are functions.
All objects in JavaScript descend from the parent Object constructor. They have many useful built-in methods we can use and access to make working with individual objects straightforward.
There are three kinds of properties:
- Properties (or named data properties) Normal properties in an objectβthat is, mappings from string keys to values. Named data properties include methods. This is by far the most common kind of property.
- Accessors (Getters/Setters) (or named accessor properties) Special methods whose invocations look like reading or writing properties. Normal properties are storage locations for property values; accessors allow you to compute the values of properties. They are virtual properties.
Internal properties
Exist only in the ECMAScript language specification. They are not directly accessible from JavaScript, but there might be indirect ways of accessing them. The specification writes the keys of internal properties in brackets. For example,[[Prototype]]
holds the prototype of an object and is readable viaObject.getPrototypeOf()
.Object Literals
JavaScriptβs object literals allow you to directly create plain objects (direct instances of Object).
In the following code snippet an object literal is used to assign an object to the variable Irene. The object has the two properties: name and describe. describe is a method:
let irene = {
name: 'Irene',
describe: function () {
return 'Person named '+this.name; // (1)
}, // (2)
};
- Use this in methods to refer to the current object (also called the receiver of a method invocation).
- in ECMAScript 5 allows a trailing comma (after the last property) in an object literal.
- A trailing comma is useful, because it helps to rearrange properties without having to worry which property is last.
You may get the impression that objects are only maps from strings to values. But they are more than that: they are real general-purpose objects, we can use inheritance between them.
For example with the Prototype relationship between objects
The prototype relationship between two objects is about inheritance
: every object can have another object as its prototype
. Then the former object inherits all of its prototypeβs properties.
But for now let's stay focus on the basics.
Create an object
In JavaScript object is a collection of properties where each property has a value associate with the key.
Use curly brackets {β¦}
to create an object.
Pay attention to the following:
let empty = {};
To create an object with properties, using the key : value pair.
let mobile = {
name: 'apple',
model: 's7',
price: ' ββ¬800'
};
The mobile object has three properties name, model, and price with the corresponding values 'apple', 's7' and ' ββ¬ 800'.
Accessing objects properties
There are two ways to access the property of an object, see the following: the dot notation and array-like notation.
The dot notation (.)
The following syntax shows how to use the dot notation to access a property of an object:
objectName.propertyName
In order to access the name property of the mobile object, you use the following expression:
mobile.name
The following snippet creates a mobile object and console name and model of mobile objects:
let mobile = {
name: 'apple',
model: 's7',
price: 'ββ¬800'
};
console.log(mobile.name);
console.log(mobile.model);
Array-like notation ( [])
The following syntax shows how to access the value of an objectβs property via the array-like notation:
objectName['propertyName'];
for example:
let mobile = {
name: 'apple',
model: 's7',
price: 'β¬800'
};
console.log(mobile['name']);
console.log(mobile['price']);
Suppose, you have property with contains spaces, you need to place it inside quotes.
Pay attention the following:
let homeAddress = {
'house nom': 39,
street: 'GΓΆtelstr.',
state: 'Berlin',
country: 'Germany'
};
To access the 'house nom', you must use the array-like notation:
homeAddress['house nom'];
If you use the dot notation, you will get an error:
homeAddress.'house nom';
Reading from a property that does not exist will result in an undefined. For example:
console.log(homeAddress.district);
// Output: undefined
Change the propertyβs value
To change the value of a property, you use the assignment operator. For example:
let mobile = {
name: 'apple',
model: 's7',
price: 'β¬800'
};
mobile.name = 'Motorola';
console.log(mobile);
//Output: {name: "Motorola", model: "s7", price: "β¬800"}
Add a new property to an object
The following expression adds the weight property to the mobile object and assigns 150g to it:
let mobile = {
name: 'apple',
model: 's7',
price: 'β¬800'
};
mobile.name = 'Motorola';
mobile.weight= '150g';
console.log(mobile);
// {name: "Motorola", model: "s7", price: "β¬800",
weight: "150g"}
Delete a property of an object
Using delete operator, To delete a property from an object:
delete objectName.propertyName;
The following example removes the price property from the mobile object:
delete mobile.price;
How to check if a property exists:
Using the in
operator, You can check if a property exists in an object:
propertyName in objectName
The following example creates a mobile object and uses the in
operator to check if the model
and weight
properties exist in the object.
let mobile = {
name: 'apple',
model: 's7',
price: 'β¬800'
};
console.log('model' in mobile);
console.log('weight' in mobile);
// Output:
true
false
Iterate over properties of an object using for...in
loop
π To iterate
over all properties of an object without knowing property names, you use the for...in
loop, have a look at the following syntax:
for(let key in object) {
// ...
};
The following shows, to creates abook
object and iterates over its properties using the for...in
loop:
let book = {
title: 'JavaScript',
tags: ['es6', 'javascript', 'node.js'],
price: 'β¬35'
};
for (const key in book) {
console.log(book[key]);
}
Functions
The following syntax shows how to tag function to the book object:
let book = {
title: 'JavaScript',
price: 'β¬35'
};
book.tag = function () {
return ['es6', 'javascript', 'node.js']
}
console.log(book.tag());
//Output: ["es6", "javascript", "node.js"]
In this example, a function expression is added to create the function and assigned it to the property tag of the book object.
Then, the function is called via the tag property as tag()
.
πWhen a function is a property of an object, it is called a method.
In ES6, you can even make it more concise:
let book = {
title: 'JavaScript',
price: 'β¬35',
tag() {
return ['es6', 'javascript', 'node.js']
}
};
console.log(book.tag());
The this
object properties
Suppose you have an array and you want to concatenate two objects properties inside the function, you can use this object properties.
π Inside the method, the this value references the object that contains the method so you can access an object property using the dot notation:
this.propertyName
The following example uses the this value in the getName() method:
let ps = {
firstName: 'Irene',
lastName: 'Smith',
getName: function () {
return this.firstName + ' ' + this.lastName;
}
};
console.log(ps.getFullName());
//Output: Irene Smith
RECAP
In this article, you have learned the following:
- An
object
is a collection of properties where each property has a value associate with thekey
. An object property key is a string and value can be any valid value. - Use the dot notation
( .)
or array-like notation([])
to access an object property. - The delete operator removes a property from an object.
- The
in
operator check if a property exists in an object. - The
for...in
iterates over properties of an object. - When functions are properties of an object, they are called methods.
- Use the this inside the method to access the objectβs properties.
I have written this article as a student's guide for my workshop aboutJavaScript Objects organised for DCI new students.
Happy coding!
Top comments (0)