In this tutorial. we will learn more about the Properties of Javascript objects. We will how to create a Property, how to add a Property, how to access it and how to delete it.
Table of Contents
What is a Property
Object in JavaScript is an unordered collection of Key-Value pairs. Each key-value pair is known as Property. Where key is the name of the Property. JavaScript uses it to search for the Property in the collection.
You can also think of property as a variable attached to the JavaScript object. They are similar to a regular variable but attached to the Object.
The Javascript objects can have any number of properties. You can also create an empty object without any properties.
The key or name of the property must be unique. The property name must be a string. (But can also be a symbol type). No two properties can have the same name.
We can assign value to the Property, just like we assign value to a regular variable. The value of the Property can be a primitive value, object, function, or special getters and setters methods.
There are two kinds of Properties. Data Property & Accessor Property
Data Property
If the value of the property is a primitive value, object, or function then the property is Data Property.
Note that when the value of a property is a function, then we call the property a method.
Accessor Property
If the property consists of getter and setter methods, then we call the property accessor property.
The JavaScript also maintains several properties for internal purposes only. Hence they are not directly accessible. For Example, internal property [[Prototype]] points to the prototype of an object. We cannot directly access it, But indirectly we can read it using the method Object.getPrototypeOf().
Creating Object Property
We usually create a Property when we create a Javascript object. JavaScript also allows us to add or delete properties even after the creation of the object.
There are many ways in which you can create a Javascript object. For Example, the following code creates the person object consist of three properties firstName, lastName & age using the object literal syntax
1 2 3 4 5 6 7 | var person = { firstName: "Allie", //FirstName Property lastName: "Grater", //lastName Property age: 50 //age Property }; |
Adding a new Property
You can add a new property just by assigning a value. In the following example, we assign value to the mobile property. Since the mobile property does not exist in the person object, JavaScript creates it and attaches it to the object.
1 2 3 4 | person.mobile = "999111999" person.city= "New York" |
If the Property already exists the second property overwrites the first. In the example, we declare firstName again and it overwrites the previous value of the firstName.
1 2 3 4 5 6 7 8 9 10 11 | var person = { firstName: "Allie", lastName: "Grater", age: 50 , firstName:"test" }; console.log(person.firstName) //test |
defineProperty
You can also add a new Property using the defineProperty method.
The Syntax for creating a new Property is as shown below.
1 2 3 | Object.defineProperty(obj, prop, descriptor) |
Whereobj
: The object on which to define the property.prop
: The name or Symbol of the property to be defined or modified. descriptor
: The descriptor for the property being defined or modified
The following example creates a new empty object person
. We then add a new property firstName
to it using the defineProperty
method.
The third parameter of defineProperty
method is the property descriptor object. We can use it to give a value to the property and also configure the property by setting its writable
& enumerable
& configurable
flags.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var person = {}; // Creates a new object //Adding n new property using defineProperty Object.defineProperty(person, 'firstName', { value: "Bill", writable: true, enumerable: true, configurable: true }); console.log(person) //{firstName: "Bill"} |
Accessing the Javascript Property
There are two ways to access a property in JavaScript
- Dot notation
- Bracket notation
Dot Property Accessor
This is the most common way to access the Property. The syntax for accessing the property using the dot notation is as follows
1 2 3 | expression.property |
Where
expression
is the object or and expression that should evaluate to object.
identifier
is the name of the property that you want to access. It must be a valid JavaScript identifier
For Example
1 2 3 4 5 6 7 8 9 10 | var person = { firstName: "Allie", lastName: "Grater", age: 50 , }; person.firstName //Allie |
You can use dot notation only if the property name follows the rules of JavaScript identifiers
- Can contain only letters,
$
,_
, and digits (0-9) - Should not start with a digit.
- No Spaces
Square Bracket Property Accessor
Square Brackets are another way to access the Property of a JavaScript Object. And It is the only way if the property name does not follow the rules of JavaScript identifiers. The Syntax is as shown below.
1 2 3 | expression[property] |
In the following example, full name
property contains space. Space is not allowed as an identifier in JavaScript. But you can use it as the property name. But cannot access it using the dot notation. The only way to access it is using the Square Bracket
1 2 3 4 5 6 7 | var person = { "full name":"Allie Grater", }; person["full name"] //Allie Grater |
Setting Properties
You can use the assignment operator (=) to set the value of a property referred to via the dot notation or bracket notation. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | var person = { age: 50 , "full name":"Allie Grater", }; person.age=60 person["full name"]="Hugo First" console.log(person) //{age: 60, full name: "Hugo First"} |
When the property doesn’t exist, JavaScript will create it. Hence you need to be careful.
In the following example, we mistype full name
as ful name
. The JavaScript just creates a new property with that name and does not give any warning.
1 2 3 4 5 6 7 8 9 10 11 12 | var person = { age: 50 , "full name":"Allie Grater", }; person.age=60 person["ful name"]="Hugo First" console.log(person) // {age: 60, full name: "Allie Grater", ful name: "Hugo First"} |
Property Names
You can use any valid string literal or Symbol as a Property Name.
We can even use the Reserved words as the property name. For Example, words like var
& function
etc are perfectly ok as Property Name (but not recommended)
The following example shows
1 2 3 4 5 6 7 8 9 10 | var person = { function: 50 , // function as property name var:1000 // keyword }; console.log(person.function) //50 console.log(person.var) //1000 |
You can also use any arbitrary string as Property Name. But we must use quotes around them. Also, you can access them only using bracket notation.
1 2 3 4 5 | var obj = { 'not an identifier': 123 }; console.log(obj['not an identifier']) //123 |
Computed Property Names
From ES6, you can use the expression inside the square brackets( []
) to create computed property name. The JavaScript evaluates the expression and uses the return value as Property Name
1 2 3 4 5 6 7 8 9 10 11 | var prefix='book_' book= {} book[prefix+'title']="Eloquent JavaScript" book[prefix+'author']="Marijn Haverbeke" console.log(book.book_title) console.log(book.book_author) |
You can refer to the Computed Property Names in JavaScript
Deleting the Javascript Property
The delete operator allows us to remove property from the object. It will remove the key-value pair from the object.
1 2 3 4 5 6 7 8 9 10 11 12 | obj = { foo:'1', boo:'2' } console.log(obj) {foo: "1", boo: "2"} delete obj.foo console.log(obj) {boo: "2"} |
Trying to access and property that does not exist returns undefined. Hence deleted Property returns undefined. But note that you can also set a property to undefined, the Property still exists but has the value undefined. Hence merely checking for undefined does not tell you whether the property does exist or not.
You can only delete the property owned by the object. You cannot delete the inherited properties (i.e. Prototype Properties).
You can read more about Deleting a Property in JavaScript
Read More