New to Rust? Grab our free Rust for Beginners eBook Get it free →
JavaScript Objects Explained with Examples for Beginners JS objects explained: Create, access and manage obj in JavaScript

A JS object is a collection of key-value pairs that lets you store and work with related data under a single variable. If you write JavaScript for more than a few hours, you run into objects constantly: from DOM nodes to API responses to config maps. This guide walks through every major way to create a js object, how to read and write properties, how methods and nesting work and the modern ES6+ patterns you need for production code.
What is a JavaScript object?
Every value in JavaScript is either a primitive (number, string, boolean, null, undefined, Symbol, BigInt) or an object. Arrays, functions, dates and DOM nodes are all objects under the hood. A plain object is just a bag you label: each label is a key, each thing you put in is a value.
const user = {
name: "Ravi",
age: 29,
active: true
};
Output:
{ name: 'Ravi', age: 29, active: true }
Keys are always converted to strings internally (except for Symbol keys). Values can be primitives, other objects, arrays or functions. That flexibility is what makes objects the workhorse of JavaScript data modeling.
How to create a JS object
Object literal syntax
The object literal {} is the preferred way to create an obj in JavaScript for almost every use case. It is concise, readable and slightly faster than the constructor approach because the engine does not have to call a function.
const product = {
id: 101,
name: "Keyboard",
price: 3499,
inStock: true
};
console.log(product.name); // Keyboard
console.log(product.price); // 3499
You can define an empty object and add properties later:
const config = {};
config.debug = false;
config.timeout = 5000;
new Object() constructor
This creates the same result as the literal but is more verbose and has no practical advantage in modern code.
const car = new Object();
car.make = "Toyota";
car.model = "Corolla";
car.year = 2022;
console.log(car);
// { make: 'Toyota', model: 'Corolla', year: 2022 }
Prefer the literal over new Object(). The literal form is cleaner and slightly faster because no constructor call is made.
Constructor function
Before ES6 classes landed in 2015, constructor functions were how you created multiple objects of the same shape. A constructor is a regular function you call with new.
function Person(name, age) {
this.name = name;
this.age = age;
}
const alice = new Person("Alice", 31);
const bob = new Person("Bob", 27);
console.log(alice.name); // Alice
console.log(bob.age); // 27
When you call a function with new, JavaScript creates a blank object, sets this to that object, runs the function body and returns the object. Methods you add to Person.prototype are shared across all instances.
Person.prototype.greet = function () {
return `Hi, I'm ${this.name}`;
};
console.log(alice.greet()); // Hi, I'm Alice
ES6 class syntax
The class in JavaScript syntax is syntactic sugar over the constructor/prototype pattern. It does the same thing but reads more like what developers from other languages expect.
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
speak() {
return `${this.name} says ${this.sound}`;
}
}
const dog = new Animal("Rex", "woof");
console.log(dog.speak()); // Rex says woof
Object.create()
Object.create(proto) creates a new object whose prototype is set to proto. This gives you fine-grained control over the prototype chain without writing a constructor.
const vehicleProto = {
describe() {
return `${this.make} ${this.model}`;
}
};
const bike = Object.create(vehicleProto);
bike.make = "Trek";
bike.model = "FX3";
console.log(bike.describe()); // Trek FX3
Accessing object properties
Dot notation
Dot notation is the default for property access. Use it when you know the property name at write time.
const config = {
host: "localhost",
port: 5432,
ssl: true
};
console.log(config.host); // localhost
console.log(config.port); // 5432
Bracket notation
Bracket notation evaluates whatever expression you put inside. This is the only way to access a property with a name that is a variable, contains spaces or starts with a digit.
const key = "port";
console.log(config[key]); // 5432
const stats = { "max requests": 200 };
console.log(stats["max requests"]); // 200
Optional chaining
Optional chaining (?.) short-circuits to undefined instead of throwing when you access a property on a null or undefined value. This appears constantly in API response handling.
const response = null;
console.log(response?.data?.user); // undefined (no error thrown)
Object property operations
Adding and modifying properties
Properties can be added or changed at any time. JavaScript objects are open by default.
const order = { id: 55, status: "pending" };
order.total = 799; // add
order.status = "confirmed"; // modify
console.log(order);
// { id: 55, status: 'confirmed', total: 799 }
Deleting properties
The delete operator removes a property entirely. After deletion, accessing that key returns undefined.
const session = { token: "abc123", expires: 3600, debug: true };
delete session.debug;
console.log(session);
// { token: 'abc123', expires: 3600 }
Checking if a property exists
The in operator returns true if a key exists anywhere in the prototype chain. hasOwnProperty() limits the check to the object’s own properties.
const obj = { role: "admin" };
console.log("role" in obj); // true
console.log("toString" in obj); // true (inherited)
console.log(obj.hasOwnProperty("role")); // true
console.log(obj.hasOwnProperty("toString")); // false
For modern code you can also use Object.hasOwn(obj, key) which does the same thing as hasOwnProperty but does not depend on the object having that method available.
JavaScript object methods
A method is just a function stored as a property value. Inside a method, this refers to the object the method was called on.
const timer = {
label: "countdown",
seconds: 60,
tick() {
this.seconds -= 1;
return `${this.label}: ${this.seconds}s left`;
}
};
console.log(timer.tick()); // countdown: 59s left
console.log(timer.tick()); // countdown: 58s left
The shorthand method syntax (tick() {}) is functionally equivalent to tick: function() {} but cleaner. Avoid arrow functions as methods because they do not bind their own this. Arrow functions capture this from the surrounding scope at definition time, which is rarely what you want for an object method.
const broken = {
name: "test",
// Arrow function: `this` is NOT the object here
getName: () => this.name
};
console.log(broken.getName()); // undefined (in strict mode)
You can read more about how JavaScript operators like typeof interact with objects and methods.
Nested objects
A nested object is an object whose property value is itself another object. This maps naturally to structured data like API payloads.
const order = {
id: 1024,
customer: {
name: "Priya",
address: {
city: "Bengaluru",
pincode: "560001"
}
},
items: [
{ sku: "KB01", qty: 1 },
{ sku: "MS02", qty: 2 }
]
};
console.log(order.customer.name); // Priya
console.log(order.customer.address.city); // Bengaluru
console.log(order.items[0].sku); // KB01
Bracket notation works the same way at each level:
console.log(order["customer"]["address"]["pincode"]); // 560001
When nesting goes several levels down, combine optional chaining with nullish coalescing to write safe access without piling up if checks:
const city = order?.customer?.address?.city ?? "Unknown";
You can see this pattern used alongside JavaScript if/else conditions to route program logic based on object state.
Iterating over objects
for…in
for...in iterates over all enumerable string keys including inherited ones. Always pair it with hasOwnProperty or Object.hasOwn if you only want the object’s own keys.
const scores = { alice: 95, bob: 87, carol: 92 };
for (const name in scores) {
if (Object.hasOwn(scores, name)) {
console.log(`${name}: ${scores[name]}`);
}
}
// alice: 95
// bob: 87
// carol: 92
Object.keys(), Object.values(), Object.entries()
These static methods return plain arrays, so you can use all JavaScript array methods on them: map, filter, reduce and so on.
const prices = { shirt: 799, jeans: 1499, shoes: 2299 };
Object.keys(prices);
// ['shirt', 'jeans', 'shoes']
Object.values(prices);
// [799, 1499, 2299]
Object.entries(prices);
// [['shirt', 799], ['jeans', 1499], ['shoes', 2299]]
// Sum all prices
const total = Object.values(prices).reduce((sum, p) => sum + p, 0);
console.log(total); // 4597
ES6+ object features
Shorthand properties
When a variable name matches the property name you want, you can omit the repetition:
const name = "Claude";
const score = 98;
// Old way
const result = { name: name, score: score };
// ES6 shorthand
const result = { name, score };
Computed property keys
Square brackets inside an object literal let you compute the key name at runtime:
const prefix = "user";
const payload = {
[`${prefix}Id`]: 42,
[`${prefix}Name`]: "Ravi"
};
console.log(payload);
// { userId: 42, userName: 'Ravi' }
This is handy when building objects with runtime-computed keys. For example, mapping over an array and collecting results by a computed field.
Object spread and Object.assign()
Spread copies enumerable own properties from one object into another. This gives you a shallow clone.
const defaults = { theme: "light", lang: "en", pageSize: 20 };
const userPrefs = { lang: "hi", pageSize: 50 };
const settings = { ...defaults, ...userPrefs };
// { theme: 'light', lang: 'hi', pageSize: 50 }
Properties on the right overwrite matching keys from the left. Object.assign() does the same but mutates the first argument instead of creating a new object:
const merged = Object.assign({}, defaults, userPrefs);
Both produce a shallow clone. If your object has nested objects as values, those inner objects are still shared by reference.
Object destructuring
Destructuring pulls named properties out of an object into individual variables. You can set defaults and rename while destructuring.
const { name, age = 18, role: userRole } = { name: "Dev", role: "admin" };
console.log(name); // Dev
console.log(age); // 18 (default applied)
console.log(userRole); // admin (renamed)
Destructuring in function parameters is especially useful because it documents what the function actually needs from a large config object.
function connect({ host, port = 5432, ssl = false }) {
return `${ssl ? "https" : "http"}://${host}:${port}`;
}
console.log(connect({ host: "db.example.com", ssl: true }));
// https://db.example.com:5432
You can see how string interpolation with template literals makes these kinds of string-building patterns cleaner.
Checking the type of an obj in JavaScript
typeof returns "object" for plain objects, arrays and null. To tell them apart, use Array.isArray() for arrays and a null check for null.
const obj = { a: 1 };
const arr = [1, 2, 3];
const none = null;
console.log(typeof obj); // "object"
console.log(typeof arr); // "object"
console.log(typeof none); // "object"
console.log(Array.isArray(arr)); // true
console.log(none === null); // true
console.log(obj !== null && typeof obj === "object"); // true
For constructor-based objects you can also check with instanceof:
class Dog {}
const rex = new Dog();
console.log(rex instanceof Dog); // true
Object vs Map: when to use which
Plain objects are fine for most use cases, but JavaScript’s Map type is better in certain situations.
| Scenario | Use object | Use Map |
|---|---|---|
| Fixed known keys | Yes | No need |
| Keys added at runtime (unknown at write time) | Possible | Better |
| Keys of any type (not just strings) | No | Yes |
Need to check size with .size | Manual (Object.keys(o).length) | Yes |
| Need insertion-order iteration guaranteed | Mostly yes (modern engines) | Yes, spec-guaranteed |
| JSON serialization | Direct | Requires conversion |
A Map also avoids prototype collision. Plain objects inherit keys like constructor and toString from Object.prototype, which can cause bugs if you use them as generic key-value stores.
Common mistakes with JS objects
Accidentally mutating a shared object
const base = { level: 1 };
const extended = base; // NOT a copy
extended.level = 2;
console.log(base.level); // 2 (base was mutated too)
Fix: spread into a new object before mutating.
const extended = { ...base, level: 2 };
Using == instead of checking structure
Two different object literals are never equal with == or ===, even if they contain the same data, because equality checks the reference.
const a = { x: 1 };
const b = { x: 1 };
console.log(a === b); // false
To compare object contents, serialize to JSON (for simple flat objects) or write a structural-equal function.
Accessing deeply nested properties without guarding
const response = fetchSomeApi(); // might be null
console.log(response.data.user); // TypeError if response is null
Use optional chaining instead:
console.log(response?.data?.user);
You can reach for a switch statement to handle multiple possible shapes of an object response cleanly.
Key takeaways
- A js object stores data as key-value pairs called properties, where keys are strings (or Symbols) and values can be any type
- Object literal syntax
{}is the fastest and most readable way to create an obj in JavaScript - Properties are read and written using dot notation (
obj.key) or bracket notation (obj["key"]) - Methods are functions stored as property values and can reference the object through
this - ES6 brought destructuring, shorthand properties, computed keys and spread that make working with objects much cleaner
Object.keys(),Object.values()andObject.entries()are the standard ways to iterate over an object’s data- Objects are reference types: copying a variable copies the reference, not the data
Frequently Asked Questions (FAQ)
What is an obj in JavaScript?
An obj in JavaScript is a variable that holds key-value pairs called properties. The values can be any data type including functions, arrays and other objects.
How do you create a js object?
The most common way is the object literal: const obj = { key: value }. You can also use constructor functions, ES6 classes or Object.create().
What is the difference between dot notation and bracket notation?
Dot notation (obj.key) works when you know the property name at write time. Bracket notation (obj["key"] or obj[variable]) works when the key is a variable or contains characters not allowed in identifiers.
How do you check if a key exists in a JavaScript object?
Use the in operator ("key" in obj) for own and inherited keys or Object.hasOwn(obj, "key") for own properties only.
How do you copy a JavaScript object?
Use spread for a shallow copy: const copy = { ...original }. For a full copy of nested objects, use structuredClone(original) in modern environments.
Can a JavaScript object method access its own properties?
Yes. Inside a regular function method, this refers to the object it was called on, so this.propertyName reads the property. Arrow functions do not work the same way because they do not bind their own this.
What is the difference between an object and an array in JavaScript?
Both are objects internally, but arrays are ordered collections indexed by integers. Plain objects are key-value stores with string or Symbol keys. Use arrays when order matters and you need integer indexes.


