JavaScript Objects Arrays: Complete Tutorial
Learn how to create JavaScript objects, work with key-value pairs, and understand why objects are the backbone of almost every JavaScript program.
A JavaScript object is a collection of key-value pairs. Think of it as a labeled container where each label, the key or property name, points to a value. That value can be a string, a number, a boolean, an array, another object, or even a function.
You use objects whenever you need to group related pieces of data together under one name. A user profile, a product listing, a DOM element configuration, or an API response are all naturally represented as objects.
const user = {
name: "Alex",
age: 28,
isAdmin: false
};The curly braces {} create an object with three properties. Inside the braces, each line is a key, a colon, and a value separated by commas. This is called an object literal.
console.log(user.name); // "Alex"
console.log(user.age); // 28Dot notation reads a value by its key name. Keys are always strings, even when you write them without quotes. Values can be any JavaScript type.
Creating Objects
JavaScript gives you several ways to create an object. Most of the time you will reach for the literal syntax.
Object Literal (Recommended)
The curly brace syntax is the simplest and most common way to create an object. Start with an empty object or define properties inline:
// Empty object
const empty = {};
// Object with properties
const book = {
title: "JavaScript: The Good Parts",
author: "Douglas Crockford",
pages: 176,
published: true
};Access any property with dot notation to read its value. The dot is followed by the exact property name you used when the object was created, so writing book, a dot, and title reads that key back out:
console.log(book.title); // "JavaScript: The Good Parts"Objects stay editable after you create them. You can add a brand new property, update one that already exists, or delete one you no longer need, all using the same object variable:
const car = { brand: "Toyota" };
car.model = "Corolla"; // Add a property
car.brand = "Honda"; // Update a property
delete car.model; // Remove a property
console.log(car); // { brand: "Honda" }You can freely add, change, and remove properties after creating an object. JavaScript objects are dynamic; their shape is not locked at creation time.
The Object Constructor
The new Object() constructor also creates an object, but it is rarely used. The literal syntax is shorter and more common:
const obj1 = new Object();
obj1.color = "blue";
const obj2 = {}; // Same result, preferred
obj2.color = "blue";Both produce the same kind of object. Stick with the object literal syntax.
Object.create()
Object.create() creates a new object with a specified prototype. This is an advanced technique you will encounter when working with inheritance. For everyday object creation, the literal syntax is all you need:
const proto = { greet() { return "hello"; } };
const obj = Object.create(proto);
console.log(obj.greet()); // "hello"For now, focus on object literals.
Properties and Values
An object property has a key and a value. Keys are strings or symbols, though strings are far more common in everyday code.
const product = {
id: 101,
name: "Wireless Mouse",
price: 29.99,
inStock: true,
tags: ["electronics", "computer", "wireless"],
details: {
brand: "Logitech",
weight: 90
}
};This object has:
| Property | Value Type | Example Use |
|---|---|---|
| id | Number | Numeric identifier |
| name | String | Display label |
| price | Number | Decimal value |
| inStock | Boolean | Yes/no flag |
| tags | Array | List of related strings |
| details | Object | Nested structured data |
A property can hold any JavaScript value, including other objects and arrays. This nesting lets you model complex real-world data in a natural way.
Access nested values by chaining dot notation:
console.log(product.details.brand); // "LogiTech"
console.log(product.tags[0]); // "electronics"Chaining dots reaches into nested objects. Bracket notation with a number index gets an item from a nested array.
Objects vs Arrays
Objects and arrays look similar because both use bracket syntax, but they solve different problems:
| Object | Array | |
|---|---|---|
| Purpose | Store named, structured data | Store ordered lists |
| Key type | String or Symbol | Numeric index (auto-assigned) |
| Access | obj.name or obj["name"] | arr[0] |
| Order | Insertion order (since ES2015) | Index-based order |
| Best for | Representing a single entity with properties | Representing many similar items |
// Use an object when each piece of data has a distinct meaning
const person = {
firstName: "Mia",
lastName: "Chen",
age: 32
};
// Use an array when you have a list of the same kind of thing
const scores = [95, 87, 91, 78];You can still use both together. An object can contain arrays, and an array can contain objects. The two structures complement each other. For more detail on arrays, see the article on /javascript/how-to-create-and-initialize-javascript-arrays.
Checking If a Property Exists
Before accessing a property, it is sometimes useful to check if it exists:
const config = { theme: "dark", fontSize: 14 };
console.log("theme" in config); // true
console.log("language" in config); // false
console.log(config.hasOwnProperty("theme")); // trueThe in operator checks the object and its prototype chain, so inherited properties also return true. hasOwnProperty() checks only the object's own properties. In most cases in is fine and shorter to write.
You can also check for undefined, which is simpler but has a subtle trap:
if (config.language === undefined) {
console.log("Language is not set");
}The in operator is safer than a plain equality check when a property can legitimately hold the value undefined, because it looks for the key itself rather than the value stored inside it. That distinction matters most for settings and form data, where a field can exist but still be empty:
const settings = { volume: undefined };
console.log(settings.volume === undefined); // true (but property exists)
console.log("volume" in settings); // true (correct)Objects Are Reference Types
One of the most important things to understand about objects is that they are reference types. When you assign an object to a variable, the variable holds a reference to where the object lives in memory, not a copy of the object itself:
const a = { count: 1 };
const b = a; // b points to the SAME object
b.count = 2;
console.log(a.count); // 2 (changed through b!)
console.log(a === b); // true (same reference)Two separate objects with identical content are not equal because they are different references. Each object literal creates a brand new location in memory, even when the properties inside look exactly the same, so JavaScript compares the reference, not the content:
const x = { value: 10 };
const y = { value: 10 };
console.log(x === y); // false (different objects in memory)This reference behavior is why you need care when copying objects. The article on /javascript/how-to-clone-a-javascript-object-without-errors covers safe copying techniques in detail.
Common Beginner Mistakes
Confusing property access syntax. If a property name has spaces, starts with a number, or contains special characters, you must use quotes and bracket notation:
const data = {
"full name": "Sam Rivera",
"1stPlace": true
};
console.log(data["full name"]); // Works
// data.full name would be a SyntaxError, dot notation cannot contain a spaceForgetting that keys are strings. Even unquoted keys like name are converted to a string internally. You can access them with either dot notation or bracket notation with a string:
const obj = { name: "Alex" };
console.log(obj["name"]); // "Alex" (works fine)Expecting order to matter. Objects preserve insertion order for string keys since ES2015, but do not rely on property order for logic. Use an array or a Map when order is critical.
Modifying a shared object by accident. Because objects are references, passing an object to a function lets that function change the original:
function addId(obj) {
obj.id = Math.random();
}
const user = { name: "Priya" };
addId(user);
console.log(user); // { name: "Priya", id: 0.836... } -- mutated!This is sometimes useful but often a source of bugs.
Rune AI
Key Insights
- An object is a collection of key-value pairs where each key is a string and each value can be any JavaScript type.
- Create objects with curly brace literal notation for most cases.
- Access properties with dot notation (obj.key) or bracket notation (obj["key"]).
- Objects can hold nested objects, arrays, and functions as values.
- Objects are reference types -- assigning an object to a variable copies the reference, not the object itself.
Frequently Asked Questions
What is the difference between a JavaScript object and an array?
Can object property names have spaces?
Are JavaScript objects the same as JSON?
Conclusion
Objects are the core data structure you will use every day in JavaScript. They group related values under named keys, making your code more organized and readable. Start with object literals, get comfortable with dot notation, and remember that almost everything in JavaScript is an object under the hood.
More in this topic
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.
How to Loop Through Arrays Using JS for Loops Guide
Looping through arrays is the most practical use of JavaScript for loops. Learn how to access each element by index, avoid off-by-one errors, and choose between for, for...of, and forEach.