Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Setting object members in JavaScript
In JavaScript, you can set object members (properties and methods) in several ways. This allows you to dynamically add or modify object properties after creation.
Syntax
// Dot notation
object.propertyName = value;
// Bracket notation
object["propertyName"] = value;
// Setting methods
object.methodName = function() {
// method body
};
Example: Setting Object Properties
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Setting Object Members</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
color: blueviolet;
margin: 10px 0;
}
</style>
</head>
<body>
<h1>Setting Object Members</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to set student object members and display them</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
let student = {};
BtnEle.addEventListener("click", () => {
// Setting properties using dot notation
student.name = "Rohan";
student.age = 22;
// Setting a method
student.displayInfo = function () {
resEle.innerHTML = "Name = " + this.name + " : Age = " + this.age;
};
student.displayInfo();
});
</script>
</body>
</html>
Different Ways to Set Object Members
let person = {};
// Method 1: Dot notation
person.firstName = "John";
person.lastName = "Doe";
// Method 2: Bracket notation
person["age"] = 30;
person["city"] = "New York";
// Method 3: Setting methods
person.getFullName = function() {
return this.firstName + " " + this.lastName;
};
// Display the object
console.log(person);
console.log("Full Name:", person.getFullName());
{
firstName: 'John',
lastName: 'Doe',
age: 30,
city: 'New York',
getFullName: [Function (anonymous)]
}
Full Name: John Doe
Key Points
- Dot notation: Use when property names are valid identifiers
- Bracket notation: Use for dynamic property names or names with spaces/special characters
-
Methods: Functions assigned to object properties can access other properties using
this - Dynamic: Object members can be added or modified at any time during execution
Conclusion
Setting object members in JavaScript is flexible and can be done using dot notation, bracket notation, or by assigning functions as methods. This dynamic nature makes JavaScript objects very versatile for storing and organizing data.
Advertisements
