JavaScript Enhanced Object Features
Master enhanced object literals, computed properties, method shorthand, and modern object patterns
40 min•By Priygop Team•Last updated: Feb 2026
Enhanced Object Literals
ES6 introduced several enhancements to object literals that make object creation more concise and expressive. These features include method shorthand, computed property names, and property value shorthand.
Object Enhancements
- Method Shorthand: Shorter method syntax
- Computed Properties: Dynamic property names
- Property Shorthand: Shorter property syntax
- Object.assign(): Merge objects
- Object.is(): Strict equality comparison
- Object.entries/values/keys: Object iteration
Enhanced Object Examples
Example
// Method shorthand
const calculator = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
},
multiply(a, b) {
return a * b;
}
};
console.log(calculator.add(5, 3)); // 8
// Property shorthand
const name = 'John';
const age = 30;
const city = 'New York';
const person = { name, age, city };
console.log(person); // { name: 'John', age: 30, city: 'New York' }
// Computed properties
const propertyName = 'dynamicKey';
const obj = {
[propertyName]: 'dynamic value',
['computed' + 'Key']: 'computed value',
['key${1 + 1}']: 'expression value'
};
console.log(obj); // { dynamicKey: 'dynamic value', computedKey: 'computed value', key2: 'expression value' }
// Object.assign()
const target = { a: 1, b: 2 };
const source1 = { b: 3, c: 4 };
const source2 = { d: 5 };
const result = Object.assign(target, source1, source2);
console.log(result); // { a: 1, b: 3, c: 4, d: 5 }
console.log(target); // { a: 1, b: 3, c: 4, d: 5 }
// Object.is() - Strict equality
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(+0, -0)); // false
console.log(Object.is(5, 5)); // true
// Object.entries(), Object.keys(), Object.values()
const user = {
name: 'Alice',
age: 25,
email: 'alice@example.com'
};
console.log(Object.keys(user)); // ['name', 'age', 'email']
console.log(Object.values(user)); // ['Alice', 25, 'alice@example.com']
console.log(Object.entries(user)); // [['name', 'Alice'], ['age', 25], ['email', 'alice@example.com']]
// Object iteration
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}
// Object.fromEntries()
const entries = [['name', 'Bob'], ['age', 30], ['city', 'London']];
const newObj = Object.fromEntries(entries);
console.log(newObj); // { name: 'Bob', age: 30, city: 'London' }
// Spread operator with objects
const baseConfig = { theme: 'dark', language: 'en' };
const userConfig = { theme: 'light' };
const finalConfig = { ...baseConfig, ...userConfig };
console.log(finalConfig); // { theme: 'light', language: 'en' }
// Object destructuring with defaults
const { name: userName = 'Anonymous', age: userAge = 18, role = 'user' } = user;
console.log(userName, userAge, role); // Alice 25 user
// Nested object enhancement
const config = {
api: {
baseUrl: 'https://api.example.com',
timeout: 5000
},
ui: {
theme: 'dark',
language: 'en'
},
getFullConfig() {
return { ...this.api, ...this.ui };
}
};
console.log(config.getFullConfig());
// Object with getters and setters
const circle = {
radius: 5,
get diameter() {
return this.radius * 2;
},
set diameter(value) {
this.radius = value / 2;
},
get area() {
return Math.PI * this.radius ** 2;
}
};
console.log(circle.diameter); // 10
circle.diameter = 20;
console.log(circle.radius); // 10
console.log(circle.area); // 314.15...Practice Exercise: Enhanced Objects
Example
// Exercise: Build a Configuration Manager
class ConfigManager {
constructor() {
this.config = {};
this.defaults = {};
this.validators = new Map();
}
setDefault(key, value) {
this.defaults[key] = value;
return this;
}
setValidator(key, validator) {
this.validators.set(key, validator);
return this;
}
set(key, value) {
const validator = this.validators.get(key);
if (validator && !validator(value)) {
throw new Error(`Invalid value for ${key}: ${value}`);
}
this.config[key] = value;
return this;
}
get(key) {
return this.config[key] ?? this.defaults[key];
}
has(key) {
return key in this.config || key in this.defaults;
}
merge(config) {
this.config = { ...this.config, ...config };
return this;
}
reset() {
this.config = {};
return this;
}
toObject() {
return { ...this.defaults, ...this.config };
}
fromObject(obj) {
this.config = { ...obj };
return this;
}
validate() {
const errors = [];
for (const [key, validator] of this.validators) {
const value = this.get(key);
if (!validator(value)) {
errors.push(`Invalid value for ${key}: ${value}`);
}
}
return errors;
}
}
// Exercise: Build a State Manager with Enhanced Objects
class StateManager {
constructor(initialState = {}) {
this.state = { ...initialState };
this.listeners = new Map();
this.history = [];
}
setState(updates) {
const oldState = { ...this.state };
this.state = { ...this.state, ...updates };
this.history.push({
timestamp: new Date(),
oldState,
newState: { ...this.state },
updates
});
this.notifyListeners(updates, oldState);
return this;
}
getState() {
return { ...this.state };
}
subscribe(key, listener) {
if (!this.listeners.has(key)) {
this.listeners.set(key, new Set());
}
this.listeners.get(key).add(listener);
return () => {
const keyListeners = this.listeners.get(key);
if (keyListeners) {
keyListeners.delete(listener);
}
};
}
notifyListeners(updates, oldState) {
for (const [key, value] of Object.entries(updates)) {
const listeners = this.listeners.get(key);
if (listeners) {
listeners.forEach(listener => {
try {
listener(value, oldState[key], this.state);
} catch (error) {
console.error('Listener error:', error);
}
});
}
}
}
getHistory() {
return [...this.history];
}
undo() {
if (this.history.length > 0) {
const lastChange = this.history.pop();
this.state = { ...lastChange.oldState };
this.notifyListeners(lastChange.updates, lastChange.newState);
}
}
}
// Test the configuration manager
const configManager = new ConfigManager()
.setDefault('theme', 'dark')
.setDefault('language', 'en')
.setDefault('timeout', 5000)
.setValidator('theme', value => ['light', 'dark'].includes(value))
.setValidator('timeout', value => typeof value === 'number' && value > 0);
configManager.set('theme', 'light');
configManager.set('timeout', 3000);
console.log('Config:', configManager.toObject());
console.log('Validation errors:', configManager.validate());
// Test the state manager
const stateManager = new StateManager({
user: null,
theme: 'dark',
notifications: []
});
const unsubscribe = stateManager.subscribe('user', (newUser, oldUser) => {
console.log('User changed:', { old: oldUser, new: newUser });
});
stateManager.setState({
user: { name: 'John', id: 1 },
theme: 'light'
});
stateManager.setState({
notifications: ['Welcome!', 'New message']
});
console.log('Current state:', stateManager.getState());
console.log('History length:', stateManager.getHistory().length);
stateManager.undo();
console.log('After undo:', stateManager.getState());Try It Yourself — Modern JavaScript (ES6+)
Try It Yourself — Modern JavaScript (ES6+)HTML
HTML Editor
✓ ValidTab = 2 spaces
HTML|40 lines|1824 chars|✓ Valid syntax
UTF-8