Object in JS
In short: An object (Object) in JavaScript is a "key -> value" data structure, where keys are strings or symbols, and values can be any data type (including other objects and functions).
Detailed explanation
Objects are the main way to store and organize data in JS. They let you group related values into a single entity and access them by name (keys).
javascript
const user = {
name: 'Alice',
age: 25,
isAdmin: true
};Here user is an object with three properties:
name, age, isAdmin.
1. Accessing properties
javascript
console.log(user.name); // "Alice"
console.log(user['age']); // 25You can access them via:
- dot notation (
obj.key), when the name is known; - square brackets (
obj['key']), when the name is stored in a variable.
2. Adding and removing properties
javascript
user.city = 'Kyiv'; // add a new one
delete user.isAdmin; // remove3. Iterating over an object's properties
javascript
for (let key in user) {
console.log(key, user[key]);
}Prints:
javascript
name Alice
age 25
city Kyiv4. Nested objects
javascript
const user = {
name: 'Alice',
address: {
city: 'Kyiv',
zip: '123456'
}
};
console.log(user.address.city); // "Kyiv"A property can contain another object, which lets you build complex structures.
5. Object methods (functions as properties)
javascript
const user = {
name: 'Alice',
sayHi() {
console.log(`Hi, ${this.name}!`);
}
};
user.sayHi(); // "Hi, Alice!"A function inside an object is called a method.
this inside a method refers to the object itself (user).
6. Checking if a property exists
javascript
console.log('name' in user); // true
console.log(user.hasOwnProperty('age')); // true7. Copying objects
javascript
const clone = { ...user }; // shallow copy (spread)
const deepClone = structuredClone(user); // deep copy8. Objects can be created in different ways
javascript
const obj1 = {}; // object literal
const obj2 = new Object(); // via constructor
const obj3 = Object.create(null); // without a prototypeSummary
| Property | Description |
|---|---|
| Type | Composite (reference type) |
| Stores | "Key -> value" pairs |
| Keys | Strings or symbols |
| Values | Any data type |
| Main operations | Adding, reading, removing, iterating |
| Often used for | Representing entities, settings, data |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.