Problem Statement
How do you create an object in JavaScript?
Explanation
Objects are created using curly braces with key value pairs separated by commas.
Keys are property names and values can be any data type. You can also use the new Object syntax but curly brace notation is preferred.
Objects store data as key value pairs, also called properties.
You can add, modify, or delete properties after creation.
Objects are one of the most important data structures in JavaScript.
Code Solution
SolutionRead Only
// Object literal (most common)
const person = {
name: 'John',
age: 30,
city: 'New York'
};
// Empty object
const empty = {};
// Using new Object (less common)
const obj = new Object();
obj.name = 'Jane';
// Accessing properties
console.log(person.name); // 'John' (dot notation)
console.log(person['age']); // 30 (bracket notation)
// Adding properties
person.job = 'Developer';
// Modifying properties
person.age = 31;
// Deleting properties
delete person.city;
// Nested objects
const user = {
name: 'John',
address: {
street: '123 Main St',
city: 'Boston'
}
};