DEV Community

Cover image for Understanding Objects in JavaScript
SATYA SOOTAR
SATYA SOOTAR

Posted on

Understanding Objects in JavaScript

Hello Readers 👋, Welcome to the 6th blog of this Javascript series.

Imagine you are going to work, and you carry a backpack. That backpack contains your laptop, ID card, and a pen.

Now imagine you have to carry all these items separately - laptop in one hand, ID card in your pocket, pen in another pocket. That would be messy, right?

That is exactly why we need objects in JavaScript.

Just like a backpack helps you organize your belongings in one place, an object helps you organize related information in one structure.

What are Objects and Why Do We Need Them?

In the previous blogs, we learned about variables and datatypes. We can create variables like this:

let name = "Satya"
let age = 25
let city = "Mumbai"
let isStudent = false
Enter fullscreen mode Exit fullscreen mode

But what if we have to manage information for multiple people?

let name1 = "Satya"
let age1 = 25
let city1 = "Mumbai"

let name2 = "Omm"
let age2 = 22
let city2 = "Delhi"

let name3 = "Priya"
let age3 = 24
let city3 = "Bangalore"
Enter fullscreen mode Exit fullscreen mode

This becomes messy very quickly. It is hard to manage, hard to read, and hard to pass around in functions.

Objects solve this problem.

An object is a way to group related data together. Instead of having separate variables for name, age, and city, we can have one object called person that contains all this information.

In technical terms, an object is a collection of key-value pairs. Each piece of information has a label (key) and a value.

Think of an object like a form you fill out. The form has fields (keys) like "Name", "Age", "City", and you fill in the values.

Creating Objects

There are multiple ways to create objects in JavaScript. We will focus on the most common and simple way: object literal syntax using curly braces {}.

Empty Object

let person = {}
console.log(person) // {}
Enter fullscreen mode Exit fullscreen mode

Object with Properties

let person = {
    name: "Satya",
    age: 25,
    city: "Mumbai"
}
console.log(person) 
// { name: 'Satya', age: 25, city: 'Mumbai' }
Enter fullscreen mode Exit fullscreen mode

Real World Example

let employee = {
    name: "Satya Prangya",
    role: "Full Stack Developer",
    employeeId: 101,
    isActive: true,
    salary: 50000
}
Enter fullscreen mode Exit fullscreen mode

Object diagram

Object with Different Datatypes

Remember the 7 primitive datatypes we learned? An object can store any of them as values:

let mixedObject = {
    name: "Satya",           // string
    age: 25,                 // number
    isEmployed: true,        // boolean
    skills: null,            // null
    experience: undefined,   // undefined
    id: Symbol("id"),        // symbol
    bigNumber: 12345678901234567890n  // bigint
}
Enter fullscreen mode Exit fullscreen mode

You can even store another object inside an object (nested object):

let student = {
    name: "Satya",
    age: 25,
    address: {
        street: "MG Road",
        city: "Mumbai",
        pincode: 400001
    }
}
Enter fullscreen mode Exit fullscreen mode

Accessing Object Properties

Once you have created an object, you need to access the values stored in it. JavaScript gives us two ways to do this: dot notation and bracket notation.

Dot Notation (.)

This is the most common and readable way to access object properties.

let person = {
    name: "Satya",
    age: 25,
    city: "Mumbai"
}

console.log(person.name) // Satya
console.log(person.age)  // 25
console.log(person.city) // Mumbai
Enter fullscreen mode Exit fullscreen mode

Think of it like this: you have a person object, and you want to get their name. You just put a dot and then the key name.

Bracket Notation (["key"])

This method uses square brackets and the key name as a string.

let person = {
    name: "Satya",
    age: 25,
    city: "Mumbai"
}

console.log(person["name"]) // Satya
console.log(person["age"])  // 25
console.log(person["city"]) // Mumbai
Enter fullscreen mode Exit fullscreen mode

When to Use Which?

Use dot notation when you know the exact property name. It is shorter and cleaner.

Use bracket notation when:

  1. The property name is stored in a variable
let person = {
    name: "Satya",
    age: 25,
    city: "Mumbai"
}

let key = "name"
console.log(person[key]) // Satya
// console.log(person.key) // This will NOT work (undefined)
Enter fullscreen mode Exit fullscreen mode
  1. The property name has spaces or special characters
let person = {
    "full name": "Satya Prangya",  // Key with space
    "age-value": 25                // Key with hyphen
}

// console.log(person.full name) // Syntax Error
console.log(person["full name"]) // Satya Prangya
console.log(person["age-value"]) // 25
Enter fullscreen mode Exit fullscreen mode

Updating Object Properties

Objects are mutable, which means you can change their property values after creation.

let person = {
    name: "Satya",
    age: 25,
    city: "Mumbai"
}

console.log(person) // { name: 'Satya', age: 25, city: 'Mumbai' }

// Update age
person.age = 26
console.log(person) // { name: 'Satya', age: 26, city: 'Mumbai' }

// Update city using bracket notation
person["city"] = "Pune"
console.log(person) // { name: 'Satya', age: 26, city: 'Pune' }
Enter fullscreen mode Exit fullscreen mode

You can update any property regardless of how you created it.

Adding New Properties

Objects are dynamic. You can add new properties even after the object is created.

let person = {
    name: "Satya",
    age: 25
}

console.log(person) // { name: 'Satya', age: 25 }

// Add new property using dot notation
person.city = "Mumbai"
console.log(person) // { name: 'Satya', age: 25, city: 'Mumbai' }

// Add new property using bracket notation
person["isEmployed"] = true
console.log(person) 
// { name: 'Satya', age: 25, city: 'Mumbai', isEmployed: true }
Enter fullscreen mode Exit fullscreen mode

The object grows as you add more properties.

Deleting Properties

You can also remove properties from an object using the delete operator.

let person = {
    name: "Satya",
    age: 25,
    city: "Mumbai",
    isEmployed: true
}

console.log(person) 
// { name: 'Satya', age: 25, city: 'Mumbai', isEmployed: true }

// Delete a property
delete person.city
console.log(person) 
// { name: 'Satya', age: 25, isEmployed: true }

delete person["isEmployed"]
console.log(person) 
// { name: 'Satya', age: 25 }
Enter fullscreen mode Exit fullscreen mode

When you delete a property, it is completely removed from the object.

Looping Through Object Keys

Sometimes you want to go through all the properties of an object and do something with each one. JavaScript provides the for...in loop for this purpose.

let person = {
    name: "Satya",
    age: 25,
    city: "Mumbai"
}

for (let key in person) {
    console.log(key)           // Prints the key
    console.log(person[key])   // Prints the value
}
Enter fullscreen mode Exit fullscreen mode

Output:

name
Satya
age
25
city
Mumbai
Enter fullscreen mode Exit fullscreen mode

You can format it nicely:

for (let key in person) {
    console.log(key + ": " + person[key])
}
Enter fullscreen mode Exit fullscreen mode

Output:

name: Satya
age: 25
city: Mumbai
Enter fullscreen mode Exit fullscreen mode

This is extremely useful when you don't know all the property names in advance or when you want to process all properties.

Array vs Object: What's the Difference?

This is a common confusion for beginners. Let me explain with a simple analogy.

Array is like a numbered list. You have items in a specific order, and you access them by their position (index).

Object is like a labeled cabinet. You have drawers with labels, and you access items by their label (key).

Comparison Table

Feature Array Object
Structure Ordered list Key-value pairs
Access By index (number) By key (string)
Syntax [value1, value2, value3] { key1: value1, key2: value2 }
Use Case List of similar items Describing one entity
Example ["apple", "banana", "mango"] { name: "Satya", age: 25 }

Code Comparison

// Array - when you have a list of similar items
let fruits = ["apple", "banana", "mango"]
console.log(fruits[0]) // apple (access by index)

// Object - when you have properties of one thing
let person = {
    name: "Satya",
    age: 25,
    city: "Mumbai"
}
console.log(person.name) // Satya (access by key)
Enter fullscreen mode Exit fullscreen mode

When to Use What?

  • Use arrays when you have a list of similar items and order matters (like a to-do list, list of students, shopping cart)
  • Use objects when you have properties describing one entity (like a person, a product, a user account)

Note: In JavaScript, arrays are actually a special type of object. That is why typeof [1,2,3] returns "object". But we treat them differently based on their use case.

Assignment: Student Object

Now it's your turn to practice. Create an object representing a student.

Requirements

  1. Create an object called student with these properties:

    • name (string)
    • age (number)
    • course (string)
  2. Add a new property grade (string) after creating the object

  3. Update the age property to a new value

  4. Print all keys and values of the student object using a for...in loop

Expected Solution

// Step 1: Create the object
let student = {
    name: "Satya",
    age: 25,
    course: "Full Stack Development"
}

console.log("Initial student:", student)

// Step 2: Add a new property
student.grade = "A"
console.log("After adding grade:", student)

// Step 3: Update age
student.age = 26
console.log("After updating age:", student)

// Step 4: Loop through and print all keys and values
console.log("\nStudent Details:")
for (let key in student) {
    console.log(key + ": " + student[key])
}
Enter fullscreen mode Exit fullscreen mode

Output:

Initial student: { name: 'Satya', age: 25, course: 'Full Stack Development' }
After adding grade: { name: 'Satya', age: 25, course: 'Full Stack Development', grade: 'A' }
After updating age: { name: 'Satya', age: 26, course: 'Full Stack Development', grade: 'A' }

Student Details:
name: Satya
age: 26
course: Full Stack Development
grade: A
Enter fullscreen mode Exit fullscreen mode

Try this on your own before looking at the solution. Experiment by adding more properties like email, phone, or address.

Common Mistakes to Avoid

1. Using Dot Notation with Variables

let person = { name: "Satya" }
let key = "name"

// Wrong
console.log(person.key) // undefined

// Correct
console.log(person[key]) // Satya
Enter fullscreen mode Exit fullscreen mode

2. Forgetting Quotes in Bracket Notation

// Wrong
console.log(person[name]) // ReferenceError: name is not defined

// Correct
console.log(person["name"]) // Satya
Enter fullscreen mode Exit fullscreen mode

3. Using Reserved Keywords as Keys

While you can use reserved keywords as keys, it is not recommended:

// This works but avoid it
let badObject = {
    class: "JavaScript",
    function: "Hello"
}
Enter fullscreen mode Exit fullscreen mode

4. Confusing Arrays and Objects

Remember:

  • If you have numbered positions → Array
  • If you have named properties → Object

Real World Use Cases

Objects are everywhere in JavaScript. Here are some real examples:

User Profile

let user = {
    username: "satyasootar",
    email: "satya@example.com",
    isVerified: true,
    followers: 1000,
    joinedDate: "2024-01-15"
}
Enter fullscreen mode Exit fullscreen mode

Product in an E-commerce Site

let product = {
    id: "P101",
    name: "Wireless Headphones",
    price: 2999,
    inStock: true,
    categories: ["electronics", "audio"],
    rating: 4.5
}
Enter fullscreen mode Exit fullscreen mode

Configuration Settings

let settings = {
    theme: "dark",
    fontSize: 16,
    notifications: true,
    language: "en"
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

  • Objects are collections of key-value pairs that help organize related data
  • Create objects using curly braces {}: let obj = { key: value }
  • Access properties using dot notation (obj.key) or bracket notation (obj["key"])
  • Update properties by assigning a new value: obj.key = newValue
  • Add new properties anytime: obj.newKey = value
  • Delete properties using delete obj.key
  • Loop through object properties using for...in loop
  • Use arrays for ordered lists, objects for labeled properties

Objects are fundamental to JavaScript. They help you write cleaner, more organized code. Almost everything in JavaScript is eventually built on objects, so mastering them now will make your journey ahead much smoother.


Hope you liked this blog. If there's any mistake or something I can improve, do tell me. You can find me on LinkedIn and X, I post more stuff there.

Top comments (0)