Objects: Literals, Notation, Properties, this, Destructuring, Spread/Rest
In JavaScript, objects are king. Almost everything is an object or behaves like one. At their core, objects are collections of key-value pairs, where keys are typically strings (or Symbols) and values can be any data type, including other objects or functions.
Objects are fundamental for grouping related data and functionality, representing real-world entities, and building complex data structures. This lesson will cover the various ways to create, manipulate, and work with object properties.
1. Object Literals: Creating Objects
The simplest and most common way to create an object in JavaScript is using an object literal, also known as an object initializer.
Syntax: { key: value, ... }
const person = {
name: 'Alice',
age: 30,
isStudent: false,
hobbies: ['reading', 'coding', 'hiking'],
address: {
street: '123 Main St',
city: 'Anytown'
},
greet: function() {
console.log('Hello!');
}
};
ES6 Enhancements for Object Literals:
-
Property Shorthand: If a variable name is the same as the desired property key, you can just list the variable name.
const name = 'Bob'; const age = 25; const user = { name, // Same as name: name age // Same as age: age }; // user is now { name: 'Bob', age: 25 } -
Computed Property Names: You can use an expression (enclosed in square brackets
[]) as a property key.const dynamicKey = 'fullName'; const user = { [dynamicKey]: 'Charlie Brown', ['user' + 'ID']: 123 }; // user is now { fullName: 'Charlie Brown', userID: 123 }
2. Accessing Properties: Dot vs. Bracket Notation
Once an object is created, you can access its properties using two main syntaxes: dot notation and bracket notation.
a) Dot Notation (object.propertyName)
-
Use Case: When you know the property name beforehand and it is a valid JavaScript identifier (e.g., no spaces, hyphens, or starting with a number).
-
Advantages: Cleaner, easier to read.
const car = { make: 'Toyota', model: 'Camry' }; console.log(car.make); // 'Toyota'
b) Bracket Notation (object['propertyName'])
-
Use Case:
- When the property name contains special characters (spaces, hyphens).
- When the property name is stored in a variable (dynamic access).
- When the property name starts with a number.
-
Advantages: More flexible for dynamic or unconventional property names.
const user = { 'first-name': 'John' }; console.log(user['first-name']); // 'John' const propName = 'model'; console.log(car[propName]); // 'Camry'
3. Adding, Modifying, and Deleting Properties
Object properties can be dynamically added, updated, or removed after an object has been created.
a) Adding Properties
You can add new properties to an object simply by assigning a value to a new key using either dot or bracket notation.
const user = { name: 'Alice' };
user.email = 'alice@example.com'; // Adds 'email'
user['city'] = 'Wonderland'; // Adds 'city'
// user is now { name: 'Alice', email: 'alice@example.com', city: 'Wonderland' }
b) Modifying Properties
To change the value of an existing property, simply assign a new value to it.
const product = { name: 'Laptop', price: 1200 };
product.price = 1100; // Modifies 'price'
product['name'] = 'Gaming Laptop'; // Modifies 'name'
// product is now { name: 'Gaming Laptop', price: 1100 }
c) Deleting Properties
Use the delete operator to remove a property from an object. This operator returns true if the deletion was successful, and false otherwise.
const settings = { theme: 'dark', notifications: true, sounds: false };
delete settings.sounds; // Deletes 'sounds' property
delete settings['theme']; // Deletes 'theme' property
// settings is now { notifications: true }
4. The this Keyword in Object Methods
The this keyword inside an object's method refers to the object itself, allowing you to access other properties of that object.
Rules for this in Methods:
- Regular Functions as Methods: When a function is defined as a method of an object and called using
object.method(),thisinside that method refers toobject. - Arrow Functions as Methods: Arrow functions do not have their own
thisbinding. They inheritthisfrom their lexical (enclosing) scope. This can be useful or problematic depending on the context. If an arrow function is defined as a top-level method,thismight refer to the global object (windowin browsers) orundefinedin strict mode. Use arrow functions for methods only when you explicitly want thethisfrom the surrounding scope (e.g., in a class method that needs to preservethisfor an inner callback).
5. Object Destructuring (ES6)
Object destructuring is a powerful ES6 feature that allows you to extract properties from objects and bind them to distinct variables. It makes code cleaner and more readable, especially when dealing with complex objects or API responses.
Syntax: { property1, property2 } = object;
6. Spread and Rest Operators with Objects (ES6)
The spread (...) and rest (...) operators, while using the same syntax, perform different operations depending on the context.
a) Spread Operator (...) for Objects
Used to copy or merge object properties.
- Copying Object Properties: Creates a shallow copy of an object.
- Merging Objects: Combines properties from multiple objects into a new one. If keys overlap, properties from later objects overwrite earlier ones.
b) Rest Operator (...) for Objects
Used during destructuring to collect remaining properties into a new object.
- Collecting Remaining Properties: Gathers all remaining properties of an object (that weren't explicitly destructured) into a new object.
7. Iterating Over Objects
Unlike arrays, objects are not directly iterable with for...of loops. You typically need to get an array of their keys, values, or entries.
-
for...inloop: Iterates over all enumerable properties of an object, including inherited ones. It's generally not recommended for iterating over object properties due to potential issues with inherited properties and non-guaranteed order. -
Object.keys(): Returns an array of an object's own enumerable property names (strings). -
Object.values(): Returns an array of an object's own enumerable property values. -
Object.entries(): Returns an array of an object's own enumerable[key, value]pairs.
These methods return arrays, which you can then iterate using for...of, forEach, map, etc.
Exercise: Working with Objects
Apply your knowledge of objects to solve the following challenges.

