A customer has a name, a delivery address, and a phone number. A product has a price, a stock count, and a title. In JavaScript, an object lets you keep these related details together and give each detail a name.
This guide starts with a simple product and builds up to a small shopping example. You will learn how to read and update properties, work with object methods, copy data, and handle missing values. Each code block runs independently. If arrays are still new to you, start with JavaScript Array Methods.
What is a JavaScript object?
An object holds properties. A property connects a key to a value. Think of a product card in a shop: the label tells you what a piece of information means. The key price tells us that 80 is the product price. We will use whole taka amounts in our shopping examples.
const product = {
name: "Notebook",
price: 80,
inStock: true
};
console.log(product.name); // "Notebook"
console.log(product.price); // 80
console.log(product.inStock); // trueThe curly braces create an object literal. Commas separate properties. Values can be strings, numbers, booleans, arrays, other objects, or functions. Ordinary property keys are strings or symbols. A numeric key is converted to a string. For a beginner, named string keys cover most everyday work.
Read properties with dot notation or bracket notation
Dot notation is convenient when you know the property name while writing the code. Bracket notation is useful when a variable holds the name or the name contains spaces.
const user = {
name: "Shariar",
city: "Dhaka",
"preferred language": "Bangla"
};
const field = "city";
console.log(user.name); // "Shariar"
console.log(user[field]); // "Dhaka"
console.log(user["preferred language"]); // "Bangla"
console.log(user.field); // undefineduser[field] reads the key stored in field, which is city. user.field looks for a property literally named field. Reading a missing property normally produces undefined, although inherited properties can also be found during a lookup.
Add, update, and delete properties
For a normal object literal, you can add a new property by assigning it a value. Assigning to an existing property updates it. The delete operator removes a property.
const product = { name: "Notebook", price: 80 };
product.stock = 12;
product.price = 90;
console.log(product.stock); // 12
console.log(product.price); // 90
delete product.stock;
console.log(Object.hasOwn(product, "stock")); // false
console.log(product.stock); // undefinedSetting stock to undefined would leave the property on the object. delete removes it. Some objects have restricted properties, such as non-writable or non-configurable properties. The examples here use ordinary editable object literals.
Check whether an object has a property
Object.hasOwn() checks whether the property belongs directly to the object. It works even when the property value is undefined. The in operator also searches the prototype chain, which is where an object can inherit properties.
const user = { name: "Shariar", phone: undefined };
console.log(Object.hasOwn(user, "phone")); // true
console.log(Object.hasOwn(user, "email")); // false
console.log(Object.hasOwn(user, "toString")); // false
console.log("toString" in user); // trueThis ordinary object inherits toString from Object.prototype. When validating a field that should belong directly to an API object, Object.hasOwn() makes that intention clear.
Object.keys(), Object.values(), and Object.entries()
These methods turn an object’s own enumerable string-keyed properties into arrays. For ordinary object literals, that includes the properties you normally write. They leave out inherited properties, symbol keys, and non-enumerable properties.
const product = { name: "Notebook", price: 80, stock: 12 };
console.log(Object.keys(product)); // ["name", "price", "stock"]
console.log(Object.values(product)); // ["Notebook", 80, 12]
console.log(Object.entries(product)); // [["name", "Notebook"], ["price", 80], ["stock", 12]]Use keys() when you need the field names. Use values() when only the values matter. Use entries() when you need both. Each entry is a two-item array holding a key and its value.
const marks = { english: 75, maths: 90, science: 85 };
const total = Object.values(marks).reduce((sum, mark) => sum + mark, 0);
const labels = Object.entries(marks).map(([subject, mark]) => `${subject}: ${mark}`);
console.log(total); // 250
console.log(labels); // ["english: 75", "maths: 90", "science: 85"]Property order follows language rules. Integer-index keys are listed in ascending numeric order, followed by other string keys in creation order. When your interface needs a particular order, define that order explicitly instead of relying on the way fields arrive.
Destructuring makes repeated property access shorter
Destructuring reads properties into variables. You can give a variable a different name and provide a default value. A default applies when the property is missing or its value is undefined.
const user = { name: "Shariar", city: "Dhaka", phone: null };
const { name: displayName, city, role = "reader", phone = "No phone" } = user;
console.log(displayName); // "Shariar"
console.log(city); // "Dhaka"
console.log(role); // "reader"
console.log(phone); // nullname: displayName creates a variable called displayName. The null phone value stays null because destructuring defaults only handle undefined. Destructuring an object does not remove its properties. Destructuring directly from null or undefined throws a TypeError, so handle those cases before destructuring.
Use spread syntax to copy or update an object
The spread syntax ... copies an object’s own enumerable properties into a new object. Later properties overwrite earlier properties with the same key. This makes it useful for producing an updated version while keeping the original top-level values.
const product = { name: "Notebook", price: 80 };
const updated = { ...product, price: 90, stock: 12 };
console.log(product.price); // 80
console.log(updated.price); // 90
console.log(updated.stock); // 12
console.log(updated === product); // falseThe order matters. { price: 90, ...product } would let product.price overwrite 90. Spread copies property values into a new object. It does not preserve the source object’s prototype or property descriptors.
Understand object references before copying nested data
Assigning an object to another variable gives both variables access to the same object. Updating a property through either variable changes that shared object.
const original = { name: "Shariar" };
const another = original;
another.name = "Hasan";
console.log(original.name); // "Hasan"
console.log(another === original); // true
console.log({ name: "Hasan" } === { name: "Hasan" }); // falseTwo separately created objects compare as different with ===, even when their properties look identical. Object equality checks identity. If you need to compare contents, decide which properties matter for your use case.
Spread creates a shallow copy. The outer object is new, while a nested object can still be shared. Here, changing the copied address also changes the original address.
const user = { name: "Shariar", address: { city: "Dhaka" } };
const copy = { ...user };
copy.address.city = "Chattogram";
console.log(copy === user); // false
console.log(copy.address === user.address); // true
console.log(user.address.city); // "Chattogram"To update one nested part independently, create a new object at each level you change. This pattern is helpful when updating application state.
const user = { name: "Shariar", address: { city: "Dhaka", area: "Mohammadpur" } };
const updated = {
...user,
address: { ...user.address, city: "Chattogram" }
};
console.log(user.address.city); // "Dhaka"
console.log(updated.address.city); // "Chattogram"
console.log(updated.address.area); // "Mohammadpur"
console.log(updated.address === user.address); // falseFor a deeper copy of supported data, structuredClone() is another option. It supports circular references and many built-in data types. Functions cannot be cloned this way, and custom class prototypes are not preserved as custom class instances. Choose it based on the values your object contains.
Read optional data with ?. and ??
API data sometimes has missing parts. Optional chaining, ?., stops a property access when the value immediately before it is null or undefined and produces undefined. Nullish coalescing, ??, provides a fallback only for null or undefined.
const user = { name: "Shariar" };
const delivery = { fee: 0, note: "" };
console.log(user.address?.city ?? "Address not added"); // "Address not added"
console.log(delivery.fee ?? 60); // 0
console.log(delivery.note ?? "No note"); // ""
console.log(delivery.fee || 60); // 60A delivery fee of zero can be valid. ?? keeps it. The || operator uses its fallback for any falsy value, including 0, false, and an empty string. If user itself might be null, write user?.address?.city. Optional chaining does not protect an undeclared variable or replace checks for the expected data type.
Functions inside objects are methods
A method is a function stored as a property. Method syntax gives you a convenient way to work with the object through this. In a call like product.getLabel(), this refers to product.
const product = {
name: "Notebook",
price: 80,
getLabel() {
return `${this.name}: Tk ${this.price}`;
}
};
console.log(product.getLabel()); // "Notebook: Tk 80"For ordinary functions, this depends on how the function is called. Passing getLabel around as a standalone function can lose the intended receiver. An arrow function takes this from its surrounding scope, so it is usually unsuitable for a method that needs the object through this.
Practical example: update a product in an array
A shopping app often stores products as an array of objects. Use find() to read one product, filter() to select products, and map() to build an updated list. Here we change the price of the notebook without changing the original product.
const products = [
{ id: 1, name: "Notebook", price: 80, stock: 12 },
{ id: 2, name: "Pen", price: 20, stock: 0 },
{ id: 3, name: "Pencil", price: 10, stock: 5 }
];
const selected = products.find((product) => product.id === 1);
const availableNames = products
.filter((product) => product.stock > 0)
.map((product) => product.name);
const updatedProducts = products.map((product) => {
if (product.id === 1) {
return { ...product, price: 90 };
}
return product;
});
console.log(selected?.name); // "Notebook"
console.log(availableNames); // ["Notebook", "Pencil"]
console.log(products[0].price); // 80
console.log(updatedProducts[0].price); // 90
console.log(updatedProducts[0] === products[0]); // false
console.log(updatedProducts[1] === products[1]); // trueThe updated list has a new notebook object. The unchanged pen and pencil objects are reused. Reusing unchanged objects is useful, but remember that they are still shared. If you later need to change one, create an updated object for it too.
JavaScript objects and JSON
JSON is a text format used to exchange data. An object is a value your JavaScript code can work with. JSON.stringify() converts supported values to JSON text, and JSON.parse() reads JSON text into JavaScript values.
const product = { name: "Notebook", price: 80 };
const text = JSON.stringify(product);
const parsed = JSON.parse(text);
console.log(typeof text); // "string"
console.log(text); // '{"name":"Notebook","price":80}'
console.log(parsed.name); // "Notebook"
console.log(parsed === product); // falseJSON object keys must use double quotes. JSON cannot directly represent functions, undefined, or circular references. A stringify-and-parse round trip is unsuitable as a general object cloning tool because some values are lost, changed, or cause an error. Parsing JSON also does not validate that the data has the fields and types your application expects.
Common questions about JavaScript objects
These are the points that often cause confusion when you begin working with real data.
Can an object declared with const change?
Yes. const prevents you from assigning a different value to the variable. The properties of its object can still change unless the object or its properties are restricted. Object.freeze() freezes the immediate object, while nested objects need separate handling.
Should I use an object or an array?
Use an object for named details about something, such as one product. Use an array for a list, such as the products in a shop. Arrays are also objects in JavaScript, but their indexed list behavior makes them useful for ordered collections. Array.isArray(value) checks whether a value is an array.
Why can a missing property and an existing property both return undefined?
A property may exist with the value undefined. Reading it gives the same result as reading an absent property in an ordinary object with no matching inherited property. Use Object.hasOwn() when existence matters.
Is spreading an object enough to copy everything?
Spread creates a new outer object and copies own enumerable properties. Nested objects and arrays remain shared unless you copy them as well. Plan the copy around the part of the data you need to update.
Try it with a student profile
Create a student object with a name, marks, and an address containing a city. Read the name using dot notation. Calculate the total marks with Object.values() and reduce(). Then create an updated student with a new city while preserving the original address. Finally, check a missing phone property with Object.hasOwn() and provide a display fallback with ??.
Run each step and inspect both the original and updated values. The difference between reading a property, changing a shared object, and creating a new object becomes much easier to understand when you can see the results.
Comments
Join the discussion. Sign in with Google to post; your email is never shown.