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
Dot notation in JavaScript
Dot notation is the most common way to access object properties in JavaScript. It uses a dot (.) between the object name and property name to retrieve or set values.
Syntax
objectName.propertyName
Basic Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dot Notation Example</title>
</head>
<body>
<h3>Student Information</h3>
<div id="result"></div>
<button onclick="showStudentInfo()">Show Student Details</button>
<script>
function Student(name, age, standard) {
this.name = name;
this.age = age;
this.standard = standard;
}
let student = new Student("Rohan", 18, 12);
function showStudentInfo() {
let result = document.getElementById("result");
result.innerHTML = "Name: " + student.name + "<br>";
result.innerHTML += "Age: " + student.age + "<br>";
result.innerHTML += "Standard: " + student.standard;
}
</script>
</body>
</html>
Reading Properties
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
console.log(person.firstName); // Access firstName
console.log(person.age); // Access age
John 30
Setting Properties
let car = {
brand: "Toyota",
model: "Camry"
};
// Modify existing property
car.brand = "Honda";
// Add new property
car.year = 2023;
console.log(car.brand);
console.log(car.year);
Honda 2023
Accessing Nested Properties
let employee = {
name: "Alice",
address: {
city: "New York",
country: "USA"
}
};
console.log(employee.name);
console.log(employee.address.city);
console.log(employee.address.country);
Alice New York USA
Limitations of Dot Notation
Dot notation cannot be used when:
- Property names contain spaces or special characters
- Property names are stored in variables
- Property names start with numbers
let obj = {
"first name": "John", // Contains space
"123": "number key" // Starts with number
};
// These won't work with dot notation:
// console.log(obj.first name); // Syntax error
// console.log(obj.123); // Syntax error
// Use bracket notation instead:
console.log(obj["first name"]);
console.log(obj["123"]);
John number key
Conclusion
Dot notation is the simplest and most readable way to access object properties in JavaScript. Use it when property names are valid identifiers without spaces or special characters.
Advertisements
