In JavaScript, properties are the values associated with an object. Properties are an object’s characteristics or attributes. They can store data types, including primitive values (such as booleans, numbers, and strings) or references to other objects.
In JavaScript, objects are collections of key-value pairs, where each key is a property name, and each value is the respective property’s value.
We can create an object using an
let objectName = {property1: value1, // Property name can be an identifier2: value2, // Property name can be a number"property n": value3, // Property name can be a string};
Accessing properties in JavaScript is straightforward. We can use either dot notation or bracket notation to access the values associated with object properties.
We use the dot notation to access a property of an object, as shown below:
let author = {name: 'John',age: 33,};// Let's access the properties of an objectconsole.log(author.name);console.log(author.age);
In the given code:
Lines 1–4: We create an author
object with two properties: name
and age
.
Lines 6–7: We use the dot notation to access the name
and age
properties of the author
’s object.
Another way to access a property of an object is by using the bracket notation, as shown below:
let author = {name: 'John',age: 33,};// Let's access a property of an objectconsole.log(author['name']);
In the given code:
Line 6: We use the bracket notation to access the 'name'
property of the author
’s object.
We can create a new property, or we can assign a new value to an existing property on the object, as shown below:
let author = {name: 'John',age: 33,};// Let's create a new propertyauthor.job = 'JavaScript Expert';console.log(author.job);// Let's modify an existing propertyauthor.age = 31;console.log(author.age);
In the give code:
Line 6: We create a new property (i.e., job
) for the author
’s object.
Line 9: We modify the age
property of the author
’s object.
We can also delete a specific property of an object as follows:
let author = {name: 'John',age: 33,};// Let's delete a propertydelete author.age;console.log(author.age);
In the give code:
Line 9: We delete the age
property of the author
’s object using the delete
operator.
Note: After deleting the
age
property of theauthor
’s object, theauthor.age
will return “undefined”.
In summary, JavaScript properties are the key-value pairs associated with an object. They can be accessed, added, modified, or deleted dynamically.
Free Resources