JavaScript Object Basics: Key-Value Pairs Guide
Direct Answer & Overview
A JavaScript object is a standalone entity consisting of key-value properties. Property keys are strings or Symbols, and values can be any JavaScript data type, including primitive numbers, strings, nested objects, and executable method functions.
JavaScript Source Code
const user = {
name: "Suresh",
age: 30,
role: "Frontend Engineer"
};
console.log(user);How does this JavaScript code work?
Objects are the foundational composite data structure in JavaScript. Created using object literal syntax (`{}`), objects store unordered collections of named properties. Property values can be accessed using either dot notation (`user.name`) when the key is a valid identifier, or bracket notation (`user['name']`) when keys contain special characters, spaces, or dynamic variable expressions.
What is the expected terminal output?
Executing this code in JS CodeLab produces the following stdout sequence in the developer console:
{"name":"Suresh","age":30,"role":"Frontend Engineer"}Common mistakes to avoid
- !Forgetting commas between key-value pairs inside object literals, triggering SyntaxError.
- !Attempting to use dot notation for property names containing spaces or hyphens; bracket notation must be used instead.
- !Comparing two distinct objects with === expecting property equality; JavaScript compares objects by memory reference, not structure.
- !Accidentally mutating shared object references across different modules.
Frequently Asked Questions
What is the difference between dot notation and bracket notation?
Dot notation (obj.prop) requires keys to be valid JavaScript identifiers known at authoring time. Bracket notation (obj['prop']) allows dynamic keys, variables, and property names containing hyphens or spaces.
How do you check if a property exists on a JavaScript object?
Use the 'in' operator ('name' in user) or Object.hasOwn(user, 'name') to safely verify property existence without checking against undefined.
How do you get all the keys or values of an object?
Use Object.keys(obj) to retrieve an array of property names, Object.values(obj) for property values, or Object.entries(obj) for [key, value] pairs.
Comprehensive Tutorial
Want an in-depth understanding of this topic?
Read our complete, interactive tutorial covering memory management, edge cases, and best practices.
Read the full objects tutorial →