Getting Started with JavaScript Objects: The Key to Organizing and Structuring Your Code


As your Javascript programs grow, so does the complexity of the data you need to manage.
As your Javascript programs grow, the need to manage complex data becomes more pronounced. Numbers, strings, and booleans have their limits. When you reach a point where you need to group related information in a structured format, that's where the power of Javascript objects comes in, empowering you to handle even the most intricate data structures.
Objects are king in Javascript 👑
Objects are the backbone of Javascript — they allow you to model real-world things, organise your data meaningfully, and build complex logic with less chaos. Whether you're representing a user profile, a shopping cart, or configuration settings, objects give you the power to label and manage data with clarity and purpose.
Think of an object like a box 📦 with labelled compartments. Each compartment holds a specific piece of data — a name, an email, a list of items — and you can easily look things up, change them, or add new ones.
In this article, we'll dive into the basics of Javascript objects: what they are, how they work, and why they're absolutely essential in your journey to writing scalable, maintainable, and smarter Javascript code.
Let's unlock the magic of objects and take your coding skills to the next level. 🚀
🧠 Why Objects Matter in Javascript
As we've been exploring variables, data types, and control flow, you may have noticed something.
Real-world problems often involve groups of data that belong together. Numbers, Strings, and Booleans are great for representing simple values, but they fall apart when you need to describe something more complex.
Take a user profile in a social media app: they need name
, age
, email
, friendsList
, settings
, etc.
You could try using individual variables for each piece:
let name = "Luna";
let age = 25;
let email = "luna@example.com";
But what happens when you add dozens of users? You'd be juggling hundreds of variables. Chaos! 😵
This is where objects come to the rescue. Objects allow you to group related data (and even behaviour) into a single, organised package. They're like labelled boxes—you can store different things inside and access them neatly when you need them.
With objects, our user profile becomes:
const user = {
name: "Luna",
age: 25,
email: "luna@example.com"
};
Everything is bundled together, making your code easier to read, maintain, and scale.
Objects bring:
Structure: Organise and group related data in one place.
Reusability: Pass them around functions without losing context.
Readability: Your code starts looking like English sentences.
Flexibility: You can add, remove, or update data dynamically.
If variables are the bricks of Javascript, objects are the walls and rooms—they give shape to your programs. 😛
To build scalable and maintainable applications with Javascript and its frameworks, you must master objects.
📦 Creating Objects
Object Literals: The Classic Way
The most straightforward and widely used method to create objects is through object literals {}
. This approach is not just clean and readable, but also flexible, making it a comfortable choice for many developers.
const user = {
name: "SK",
age: 29,
isActive: true
};
It's simple, declarative, and instantly tells you what the object represents.
You can store strings, numbers, booleans, arrays, other objects, or even functions (more on that later).
Objects can even be empty:
const emptyObject = {};
This creates a "blank slate" you can add properties to later.
The new Object()
Constructor
Another way is using the built-in Object constructor:
const user = new Object();
user.name = "SK";
user.age = 29;
This does the same thing, but it's more verbose.
These days, object literals are preferred because they're cleaner and easier to read.
Avoid this — object literals are simpler, safer, and more modern.
We rarely use the constructor approach unless we're doing something advanced—like creating objects from prototypes. 🛠️✨
🔍 Accessing Object Properties
There are two main ways to access (or set) object properties: dot notation and bracket notation.
Dot Notation .
This is the most common and the most readable:
console.log(user.name); // "SK"
Think of dot notation like saying: "Hey, user object, give me your name property."
However, dot notation only works if:
The property name is a valid identifier (no spaces, no special characters, doesn't start with numbers).
The property name is known at the time of writing your code.
Bracket Notation []
For more dynamic property names, you use brackets:
console.log(user["age"]); // 29
Bracket notation shines when:
Property names have spaces:
const weirdObject = { "favourite color": "blue" };
console.log(weirdObject["favorite color"]); // blue
Property names are numbers:
const scores = { 1: "Gold", 2: "Silver" };
console.log(scores[1]); // Gold
Property names stored in variables:
const key = "name";
console.log(user[key]); // SK
Rule of thumb: Use dot notation when you can, bracket notation when you must.
🪞 Working with Nested Objects
Objects can contain other objects—this is where things start to get interesting.
const user = {
name: "Luna",
profile: {
email: "luna@example.com",
social: {
twitter: "@lunaCode",
instagram: "@lunaInsta"
}
}
};
Accessing nested values:
console.log(user.profile.email); // "luna@example.com"
console.log(user.profile.social.twitter); // "@lunaCode"
But here's the problem: what if the profile doesn't exist?
console.log(user.address.city); // ❌ Error: Cannot read properties of undefined
Optional Chaining: Your Safety Net
Remember the optional chaining operator(`?.`) we discussed in All About Javascript Operators: Clean Code Tips, Gotchas & Best Practices? It's your safety net when working with nested objects. If you're still not fully comfortable with it, revisit that section — it's designed to make you feel secure when dealing with unpredictable data.
Optional chaining (?.
) makes nested access safe:
console.log(user.address?.city); // undefined (no error)
This is gold when working with APIs, user input, or any unpredictable data.
🛠 Modifying Objects: Making Changes on the Fly
One of the most incredible things about Javascript objects is that they're dynamic.
Unlike primitives (like numbers or strings), objects can grow, shrink, and evolve as your program runs.
You don't need to know all the properties ahead of time — you can add, update, or delete them whenever you need. Think of objects like backpacks: you can toss new stuff in, replace what's inside, or take things out, all while carrying the same backpack around. 🎒
Adding Properties
You can add new properties to an existing object at any time. There are two main ways to do this:
Dot notation (clean and straightforward):
user.isAdmin = true;
Previously, isAdmin
didn't exist, but it is now part of the user
object.
Bracket notation (handy when property names are dynamic or contain spaces/special characters):
const key = "lastLogin"
user[key] = "2025-08-01";
This lets you use strings or variables to set property names, giving more flexibility.
Updating Properties
If a property already exists, assigning a new value updates it:
user.name = "SK Dev";
Now, wherever you access the user.name
, you'll see "SK Dev"
instead of the original value.
Deleting Properties
When you no longer need a property, you can remove it using the delete
operator:
delete user.isAdmin;
This completely removes the property, isadmin
, from the object — as if it never existed.
⚠️ Gotcha: Objects Are Passed by Reference
Here's an important twist: deleting a property doesn't affect other variables referencing the same object because all references point to the same thing in memory. Javascript objects are passed by reference, not by value.
For example:
let user = { name: "Luna" };
let alias = user;
delete alias.name;
console.log(user.name); // undefined
Both user
and alias
refer to the same object, so deleting through one reference affects the other.
✏️ Property Value Shorthand: Less Typing, Same Power
When creating objects, we often end up repeating ourselves. For example:
const name = "Luna";
const age = 28;
const user = { name: name, age: age };
This works fine, but it feels redundant — we're writing the same thing twice (name: name
, age: age
). Javascript gives us a cleaner way to do this with property value shorthand.
If the variable name matches the property name, you can skip the repetition:
const name = "Luna";
const age = 28;
const user = { name, age };
console.log(user); // { name: "Luna", age: 28 }
Under the hood, Javascript interprets { name, age }
as { name: name, age: age }
. It's just a shortcut for cleaner, more readable code.
Why is it Useful?
- Cleaner object creation: Especially helpful when returning objects from functions.
- Less chance of typos: You avoid mismatching variable and property names.
- Great for APIs and configs: Makes your code look more professional and concise.
Example with a function:
function createUser(name, age) {
return { name, age };
}
console.log(createUser("Marco", 30));
// { name: "Marco", age: 30 }
Without shorthand, you'd have to write return { name: name, age: age }
, which gets tedious as objects grow bigger.
🕵️ Checking If a Property Exists
When working with objects, it's common to ask: "Does this property exist?"
If you try to access a missing property, Javascript won't throw an error — it just gives you undefined
. But sometimes, you need a reliable way to check whether a property exists before using it.
The in
Operator
The simplest way to check is with the in
operator.
const user = { name: "Luna", age: 28 };
console.log("name" in user); // true
console.log("email" in user); // false
Returns
true
if the property exists anywhere on the object (including its prototype).Great for quick checks, but be aware that it might detect inherited properties too.
hasOwnProperty
If you only care about direct properties (not inherited ones), use hasOwnProperty()
.
console.log(user.hasOwnProperty("age")); // true
console.log(user.hasOwnProperty("toString")); // false (comes from prototype)
Gotcha: hasOwnProperty
itself can be overridden by a property with the same name.
Normally, hasOwnProperty()
is a built-in method that lets you check if an object has a property directly on itself (not inherited from its prototype).
But here's the catch: in Javascript, objects are flexible—you can redefine almost any property, even hasOwnProperty
itself.
const obj = {
hasOwnProperty: () => false
};
console.log(obj.hasOwnProperty("name"));
What's happening?
We overwrote the built-in
hasOwnProperty
method with our own version.Now, instead of running the original method, Javascript runs our new one, which always returns
false
.Worse, if we accidentally wrote something else (like a non-function value), calling
obj.hasOwnProperty()
could throw aTypeError
because it's no longer a function.
This means that relying directly on hasOwnProperty
for objects can be risky if they come from untrusted sources (e.g., API data).
The safer approach:
Use
Object.hasOwn(obj, key)
(introduced in ES2022). It doesn't rely on any properties of the object itself.Or, call the original method explicitly:
Object.prototype.hasOwnProperty.call(obj, "name");
Further discussion on call
and prototypes will be covered in a future article that focuses on advanced functions and objects.
Modern & Safer: Object.hasOwn()
To avoid that gotcha, modern Javascript introduced Object.hasOwn()
.
console.log(Object.hasOwn(user, "age")); // true
It works like
hasOwnProperty
, but it can't be overridden.Always prefer
Object.hasOwn()
if available (ES2022+).
Objects aren't just another feature of Javascript—they're the language's backbone. Whether you're organising user profiles, managing configuration settings, or building the data models that power your favourite apps, objects give you the structure and flexibility to turn messy data into something meaningful and maintainable.
The more you work with Javascript, the more you'll notice: primitives get you started, but objects take you further. They let you bundle related data, add behaviour, adapt to changing requirements, and keep your codebase clean enough that "future you" will thank "present you." 🙌
In the following article, we'll look into iterating over objects, destructuring, and the spread & rest operators—tools that will make working with objects even more powerful and expressive. Stay tuned! ✨
Subscribe to my newsletter
Read articles from Sangy K directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Sangy K
Sangy K
An Introvert Coder | Trying to be a Full-stack Developer | A Wannabe Content Creator