What is object literal In javascripts?
What are Object Literals?
Object literals are a fundamental data structure in JavaScript that allow you to store collections of key-value pairs. They provide a way to bundle related data and functionality together in a single container.
Key Point: Object literals are containers that bundle data (properties) and functionality (methods) together, making it easier to organize and pass related information.
Creating Object Literals
Basic Object Literal Syntax
// Empty object literal
const obj = {};
// Object with properties
const product = {
productCode: 1001,
productName: "Apple"
};
// Object with method (traditional syntax)
const productWithMethod = {
productCode: 1001,
productName: "Apple",
getData: function() {
return `${this.productCode}: ${this.productName}`;
}
};
// Object with method (ES6 shorthand)
const productES6 = {
productCode: 1001,
productName: "Apple",
getData() {
return `${this.productCode}: ${this.productName}`;
}
};
console.log(productES6.getData()); // "1001: Apple"
productCode
1001
productName
“Apple”
getData()
function()
Dynamic Keys in Object Literals
Using Computed Property Names
// Dynamic key using variable
const key = "productCode";
const value = 1001;
const product = {
[key]: value, // Dynamic key
productName: "Apple"
};
console.log(product.productCode); // 1001
// Dynamic key using expression
const methodPrefix = "get";
const methodSuffix = "Data";
const advancedProduct = {
productCode: 1001,
productName: "Apple",
[methodPrefix + methodSuffix]() {
return `${this.productCode}: ${this.productName}`;
}
};
console.log(advancedProduct.getData()); // "1001: Apple"
Property Value Shorthand
ES6 Property Shorthand Syntax
const productCode = 1001;
const productName = "Apple";
// Traditional way (repetitive)
const productOld = {
productCode: productCode,
productName: productName
};
// ES6 shorthand (cleaner)
const productNew = {
productCode,
productName
};
console.log(productNew.productCode); // 1001
console.log(productNew.productName); // "Apple"
Read-Only Properties
Using Object.defineProperty()
// Create a prototype with configuration
const proto = {};
Object.defineProperty(proto, "productCode", {
value: 2001,
writable: false, // Make it read-only
configurable: true,
enumerable: true
});
// Create object from prototype
const product = Object.create(proto);
product.productName = "Apple";
console.log(product.productCode); // 2001
// Try to change read-only property
product.productCode = 3001; // This won't work in strict mode
console.log(product.productCode); // Still 2001 (not changed)
Object References vs Cloning
Reference Assignment Issues
const original = {
productCode: 1001,
productName: "Apple"
};
// Reference assignment (not a copy)
const reference = original;
// Changing property affects both objects
reference.productCode = 2001;
console.log(original.productCode); // 2001 (unexpected change!)
console.log(reference.productCode); // 2001
Creating True Clones
const original = {
productCode: 1001,
productName: "Apple"
};
// Method 1: Object.assign()
const clone1 = Object.assign({}, original);
// Method 2: Spread operator (ES6)
const clone2 = { ...original };
// Method 3: JSON methods (for simple objects)
const clone3 = JSON.parse(JSON.stringify(original));
// Verify clones are independent
clone1.productCode = 2001;
console.log(original.productCode); // 1001 (unchanged)
console.log(clone1.productCode); // 2001
Nested Objects and Methods
Complex Object Literals
const product = {
productCode: 1001,
productName: "Apple",
details: {
category: "Fruit",
origin: "USA",
nutrition: {
calories: 52,
vitamins: ["C", "K"]
}
},
getDescription() {
return `${this.productName} (${this.details.category}) from ${this.details.origin}`;
},
// Avoid arrow functions for methods
getNutrition: function() {
return `${this.details.nutrition.calories} calories`;
}
};
console.log(product.getDescription()); // "Apple (Fruit) from USA"
console.log(product.getNutrition()); // "52 calories"
Best Practices
- Use property value shorthand for cleaner code when variable names match property names
- Use computed property names for dynamic keys
- Avoid arrow functions for object methods (they don’t have their own
thisbinding) - Use
Object.assign()or spread operator to create true clones instead of references - Use
Object.defineProperty()for read-only properties when needed - Consider using JSON methods for deep cloning simple objects (no functions or circular references)