JavaScript Interview Question #28

What is the difference between dot notation and bracket notation?

Objects, Arrays & Core Data Handling Junior Beginner

Quick Interview Answer

Dot notation accesses a property with a fixed valid identifier, such as user.name. Bracket notation accepts an expression and is required when the property name is dynamic, contains characters that are invalid in an identifier, or is stored in a variable.

Detailed Explanation

Dot notation accesses a property with a fixed valid identifier, such as user.name. Bracket notation accepts an expression and is required when the property name is dynamic, contains characters that are invalid in an identifier, or is stored in a variable.

Both forms access object properties; the choice depends mainly on how the property name is represented.

Code Example

const user = {
    name: "Asif",
    "home-city": "Multan"
};

console.log(user.name);
console.log(user["home-city"]);

const propertyName = "name";
console.log(user[propertyName]);