Overview
An object in JavaScript is a basic data structure used to represent the state and functions of real-world items within a program. You can imagine it as a box where you store pairs of labels (keys) and contents (values). This article uses the status management of a smart home system to explain how to create objects, read or write data, and execute methods.
Specifications (Syntax)
Object Operations List
| Operation | Syntax Example | Features |
| Definition | const obj = { key: value, ... } | Enclosed in curly braces {} and separated by commas. |
| Get Value (1) | obj.key | Dot notation. This is the most common method. |
| Get Value (2) | obj['key'] | Bracket notation. Used when the key name is in a variable or contains special characters. |
| Update Value | obj.key = newValue | Assigning a value to an existing key overwrites it. |
| Addition | obj.newKey = value | Assigning a value to a non-existent key adds a new property. |
Basic Usage
1. Definition and Retrieval
Here is an example of storing air conditioner settings in an object.
const airConditioner = {
power: 'ON',
temp: 24,
mode: 'Cool'
};
// Retrieve using dot notation
console.log(airConditioner.temp); // 24
// Retrieve using bracket notation
console.log(airConditioner['mode']); // "Cool"
2. Update and Addition
You can change the target temperature or add new features.
// Update a value
airConditioner.temp = 25;
// Add a new property
airConditioner.timer = 60;
console.log(airConditioner);
// { power: 'ON', temp: 25, mode: 'Cool', timer: 60 }
3. Defining Methods
You can give “actions” to an object.
const robot = {
status: 'Ready',
start: function() {
console.log('Robot started');
},
// Shorthand notation introduced in ES6 (Recommended)
stop() {
console.log('Stopped');
}
};
robot.start(); // "Robot started"
Full Code (HTML / JavaScript)
This is a smart home management panel. It displays the status of living room lights and the air conditioner on the screen. Clicking buttons updates the object properties and re-renders the display.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smart Home Controller</title>
<style>
.panel {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 400px;
background-color: #222;
color: #fff;
padding: 20px;
border-radius: 12px;
box-shadow: 0 4px 10px rgba(0,0,0,0.5);
}
h3 {
margin-top: 0;
border-bottom: 1px solid #444;
padding-bottom: 10px;
color: #4fc3f7;
}
.device-card {
background-color: #333;
margin-bottom: 15px;
padding: 15px;
border-radius: 8px;
display: flex;
justify-content: space-between;
align-items: center;
}
.device-info { font-size: 0.9rem; }
.device-name { font-weight: bold; font-size: 1.1rem; display: block; margin-bottom: 5px;}
.status-badge {
padding: 4px 8px;
border-radius: 4px;
font-size: 0.8rem;
background-color: #555;
}
.status-badge.on { background-color: #4caf50; color: white; }
.status-badge.off { background-color: #f44336; color: white; }
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
button {
padding: 10px;
border: none;
border-radius: 6px;
cursor: pointer;
font-weight: bold;
transition: background 0.2s;
}
.btn-light { background-color: #ffca28; color: #333; }
.btn-temp { background-color: #29b6f6; color: white; }
button:hover { opacity: 0.9; }
</style>
</head>
<body>
<div class="panel">
<h3>My Smart Home</h3>
<div class="device-card">
<div class="device-info">
<span class="device-name">Living Light</span>
<span class="device-detail">Brightness: <span id="val-bright">--</span>%</span>
</div>
<span id="badge-light" class="status-badge off">OFF</span>
</div>
<div class="device-card">
<div class="device-info">
<span class="device-name">Air Conditioner</span>
<span class="device-detail">Temp: <span id="val-temp">--</span>°C</span>
</div>
<span id="badge-ac" class="status-badge on">ON</span>
</div>
<div class="controls">
<button id="btn-toggle-light" class="btn-light">Toggle Light</button>
<button id="btn-up-temp" class="btn-temp">Raise Temperature</button>
</div>
</div>
<script src="smart_home.js"></script>
</body>
</html>
JavaScript
/**
* Smart Home Management Script
* Practice of object definition, retrieval, and update
*/
// 1. Define object representing home state
const homeState = {
owner: 'Admin',
livingLight: {
power: false, // false=OFF, true=ON
brightness: 80
},
airConditioner: {
power: true,
temperature: 24,
mode: 'Cool'
},
// Define method for reporting status
report: function() {
console.log(`Current Temp: ${this.airConditioner.temperature}°C`);
}
};
// DOM elements
const elBright = document.getElementById('val-bright');
const elBadgeLight = document.getElementById('badge-light');
const elTemp = document.getElementById('val-temp');
const btnLight = document.getElementById('btn-toggle-light');
const btnTemp = document.getElementById('btn-up-temp');
/**
* Function to render values to the screen (Retrieval)
*/
const render = () => {
// 1. Get values from nested objects
elBright.textContent = homeState.livingLight.brightness;
// Check light status
if (homeState.livingLight.power) {
elBadgeLight.textContent = 'ON';
elBadgeLight.className = 'status-badge on';
} else {
elBadgeLight.textContent = 'OFF';
elBadgeLight.className = 'status-badge off';
}
// Get air conditioner temperature
elTemp.textContent = homeState.airConditioner.temperature;
};
/**
* Toggle light status (Update)
*/
const toggleLight = () => {
// Invert current power status
homeState.livingLight.power = !homeState.livingLight.power;
// Change brightness based on power
if (homeState.livingLight.power) {
homeState.livingLight.brightness = 100;
} else {
homeState.livingLight.brightness = 0;
}
render();
};
/**
* Raise temperature (Update)
*/
const tempUp = () => {
// Increment the current temperature
homeState.airConditioner.temperature += 1;
// Execute method
homeState.report();
render();
};
// Initial display
render();
// Event listeners
btnLight.addEventListener('click', toggleLight);
btnTemp.addEventListener('click', tempUp);
Custom Points
Bracket notation is essential when you want to use a variable as a key. For example, if you have const target = 'temperature', you cannot use homeState.airConditioner.target. Instead, you must use homeState.airConditioner[target]. Additionally, while you cannot reassign an object declared with const to a new object, you can freely modify the internal properties of that object.
Summary
You should master these three patterns for object manipulation: creating data using { key: value }, reading data with obj.key, and writing data with obj.key = newValue. In web application development, data received from a server is often in JSON format, which uses this structure. Therefore, accessing properties using dot notation is a required skill.
