Episode 2 of 11
Object Literals
Create objects using literal notation — define properties and methods directly on an object and access them with dot notation and bracket notation.
Object Literals
An object literal is the simplest way to create an object in JavaScript — define it directly with curly braces.
Creating an Object
var user = {
name: 'Shaun',
age: 30,
email: 'shaun@example.com',
location: 'Manchester',
blogs: ['Why I love JS', '10 CSS tips']
};
Accessing Properties
// Dot notation
console.log(user.name); // 'Shaun'
console.log(user.blogs); // ['Why I love JS', '10 CSS tips']
// Bracket notation
console.log(user['email']); // 'shaun@example.com'
// Bracket notation with variables
var key = 'location';
console.log(user[key]); // 'Manchester'
Adding Methods
var user = {
name: 'Shaun',
age: 30,
login: function() {
console.log('User logged in');
},
logout: function() {
console.log('User logged out');
}
};
user.login(); // 'User logged in'
user.logout(); // 'User logged out'
The this Keyword
var user = {
name: 'Shaun',
age: 30,
greet: function() {
console.log('Hello, my name is ' + this.name);
}
};
user.greet(); // 'Hello, my name is Shaun'
this refers to the object the method belongs to. Inside user.greet(), this is user.
When to Use Object Literals
| Use Case | Good Fit? |
|---|---|
| Single, one-off objects | Yes — quick and simple |
| Configuration objects | Yes — group settings together |
| Many objects of the same type | No — use classes instead |
Key Takeaways
- Object literals are created with
{ key: value }syntax - Access properties with dot notation (
obj.prop) or bracket notation (obj['prop']) thisinside a method refers to the object it belongs to- Object literals are great for single objects, but not for creating many similar objects