What are JavaScript properties and their connection to objects?
Properties
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.
Connection to 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.
Create an object
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};
Access properties of an object
Accessing properties in JavaScript is straightforward. We can use either dot notation or bracket notation to access the values associated with object properties.
Dot notation
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
authorobject with two properties:nameandage.Lines 6–7: We use the dot notation to access the
nameandageproperties of theauthor’s object.
Bracket notation
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 theauthor’s object.
Add and modify a property
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 theauthor’s object.Line 9: We modify the
ageproperty of theauthor’s object.
Delete a property
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
ageproperty of theauthor’s object using thedeleteoperator.
Note: After deleting the
ageproperty of theauthor’s object, theauthor.agewill return “undefined”.
Conclusion
In summary, JavaScript properties are the key-value pairs associated with an object. They can be accessed, added, modified, or deleted dynamically.
Free Resources