How to access an object having spaces in the object's key using JavaScript?

When object keys contain spaces, you cannot use dot notation to access them. Instead, you must use bracket notation with quotes around the key name.

The Problem with Spaces in Keys

Dot notation requires valid JavaScript identifiers, which cannot contain spaces. Keys with spaces need bracket notation.

const person = {
    'first name': 'John',
    'last name': 'Doe',
    age: 30
};

// This won't work - syntax error
// console.log(person.first name);

// This works - bracket notation
console.log(person['first name']);
console.log(person['last name']);
John
Doe

Using Bracket Notation for Spaced Keys

Bracket notation allows you to access any key, including those with spaces, special characters, or dynamic names.

const product = {
    'product name': 'Laptop',
    'unit price': 999,
    'in stock': true,
    'supplier info': 'TechCorp Ltd'
};

console.log('Product:', product['product name']);
console.log('Price: $' + product['unit price']);
console.log('Available:', product['in stock']);
console.log('Supplier:', product['supplier info']);
Product: Laptop
Price: $999
Available: true
Supplier: TechCorp Ltd

Modifying Values with Spaced Keys

You can also update object properties with spaced keys using bracket notation.

const student = {
    'full name': 'Alice Johnson',
    'grade level': 'Junior',
    'gpa score': 3.8
};

console.log('Before update:', student['grade level']);

// Update the value
student['grade level'] = 'Senior';
student['gpa score'] = 3.9;

console.log('After update:', student['grade level']);
console.log('New GPA:', student['gpa score']);
Before update: Junior
After update: Senior
New GPA: 3.9

Comparison: Dot vs Bracket Notation

Notation Syntax Works with Spaces? Dynamic Keys?
Dot obj.key No No
Bracket obj['key'] Yes Yes

Dynamic Key Access

Bracket notation also allows dynamic key access using variables.

const userInfo = {
    'user name': 'bob123',
    'email address': 'bob@example.com',
    'phone number': '555-0123'
};

const keyToAccess = 'email address';
console.log('Dynamic access:', userInfo[keyToAccess]);

// Loop through all keys
for (let key in userInfo) {
    console.log(key + ':', userInfo[key]);
}
Dynamic access: bob@example.com
user name: bob123
email address: bob@example.com
phone number: 555-0123

Conclusion

Always use bracket notation with quotes for object keys containing spaces. Dot notation only works with valid JavaScript identifiers without spaces or special characters.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements