DEV Community

Cover image for Creating and Manipulating Objects in JavaScript -Explained!
Boniface Gordian
Boniface Gordian

Posted on

Creating and Manipulating Objects in JavaScript -Explained!

Introduction

Imagine you’re moving into a new apartment. You have all your belongings packed in boxes, and each box is labeled with its contents: “Kitchen Supplies,” “Books,” “Clothes,” and so on. Now, think of each of these boxes as an object in JavaScript. Each box (object) contains various items (properties and methods) that you can access, use, or modify whenever you need.

In the world of JavaScript, objects serve as the containers for storing data and functions. They help you organize and structure your code in a way that’s easy to manage and understand. Just as you wouldn’t want to throw all your belongings into one giant, disorganized heap, you don’t want to write chaotic code. Objects are like the neatly labeled boxes that keep everything in order.

However, after publishing a recent article on Dev.to about JavaScript objects, I received some insightful feedback that sparked a bit of a debate. Here’s a summary of the key comments:

Jon Randy 🎖️ pointed out: "...where each key is a string... Unfortunately, this is not correct. Keys can also be Symbol."

GreenerSoft responded: "Or an integer and a Boolean. This is in JSON where the keys are strings."

Jon Randy 🎖️ countered: "Keys cannot be integers or Booleans, and this post has nothing to do with JSON. If you try to use anything other than a string or a symbol as an object key, it will be coerced to a string."

The discussion highlighted different perspectives, and I believe it’s important to clarify the facts to ensure everyone has a correct understanding of JavaScript objects. In response to this feedback, I’m bringing over an article I originally published on Medium to provide a more detailed explanation of JavaScript objects, particularly the nuances around object keys. Whether you’re new to coding or have been developing for years, mastering objects is crucial for writing clean, organized, and efficient code.

What Are JavaScript Objects?

Just like organizing your school materials into different compartments in your backpack or drawer, JavaScript objects help you organize your data.

Imagine you’re a student with a bunch of textbooks, notebooks, and other study materials. You don’t just throw everything into a single bag haphazardly; instead, you organize them into different sections or compartments for easy access. This is exactly how JavaScript objects work — they allow you to organize and structure your data neatly.

JavaScript objects are collections of key-value pairs, where each key is a string or a symbol (referred to as a property name), and each value can be any data type, including other objects and functions. Objects allow you to group related data and functionality together, making your code more organized and easier to work with.

Think of JavaScript objects as multi-functional storage containers. Just like a student’s backpack that contains various sections for different subjects, an object can hold different pieces of information and methods (functions) to manipulate that information.

Below is a simple example of an object representing a student’s study schedule:

let studySchedule = {
    subject: "Math",
    hoursPerWeek: 5,
    hasHomework: true,
    study: function() {
        console.log("Time to study Math!");
    }
};
Enter fullscreen mode Exit fullscreen mode

In this example:

  • subject, hoursPerWeek, and hasHomework are properties of the studySchedule object.
  • study is a method of the studySchedule object, which is a function that belongs to the object.

How to Create, access and update Object properties in JavaScript

Creating objects in JavaScript is like setting up your own personalized toolbox where you can store and organize your tools (data and functions) just the way you need them. Let’s break it down into simple steps to help you get started, with a bit of excitement thrown in!

In a previous article, I touched on the fact that object keys are strings, but I didn’t go into the full range of possibilities. Understand that JavaScript object keys can actually be either strings or symbols. If you attempt to use other data types (like numbers or booleans) as keys, they will be coerced to strings. For example:

let book = {
    title: "Every developer's guide",
    author: "Boniface Gordian",
    pages: 176,
    [42]: "This is a number key"
};

console.log(book["42"]); // Outputs: "This is a number key"

Enter fullscreen mode Exit fullscreen mode

In the example above, the number 42 is coerced into the string "42" when used as a key.

Creating an Object
Image description
To create an object in JavaScript, you use a pair of curly braces {}. Inside these braces, you define key-value pairs, where each key is a property name and each value is the property’s value.

1. Object Literal Notation
This is the simplest and most common way to create an object. You define the object and its properties in one step.

let student = {
    name: 'Boniface',
    grade: 'A',
    age: 20,
    study: function() {
        console.log("Studying hard!");
    }
};
Enter fullscreen mode Exit fullscreen mode

In this example:

  • name, grade, and age are properties of the student object.
  • study is a method (function) that belongs to the student object.

2. Using the new object() Syntax
While the object literal notation is the most common and concise way to create objects, JavaScript also provides another method known as the new Object() syntax. This method is slightly more formal and verbose, but it's useful in certain situations where you need to create objects dynamically or with a specific constructor.

let student = new Object();
student.name = 'Boniface';
student. Grade = 'A';
student.age = 25;
student.study = function() {
    console.log("Studying hard!");
};
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We start by creating an empty object using new Object(). This sets up a blank slate where we can later add properties and methods.
  • After creating the empty object, we add properties like name, grade, and age by assigning values to them using dot notation (student.name = "Boniface";).
  • We also add a method called study, which is a function that prints a message to the console when called.

Why Use new Object()?
While the object literal notation is quick and easy, the new Object() syntax is handy in situations where:

  • Dynamic Object Creation: If you need to create objects based on certain conditions or within loops, using new Object() might make your code clearer and more flexible.
  • Consistent Syntax: In some cases, using new Object() can make your code more consistent, especially if you're working in a codebase that uses constructors and the new keyword frequently.
function createStudent(name, grade, age) {
    let student = new Object();
    student.name = name;
    student.grade = grade;
    student.age = age;
    student.study = function() {
        console.log(name + " is studying hard!");
    };
    return student;
}

let student1 = createStudent("Boniface", "A", 20);
let student2 = createStudent("Michael", "B+", 19);

console.log(student1.name); // Output: Bonface
student2.study(); // Output: Michael is studying hard!
Enter fullscreen mode Exit fullscreen mode

In this example:

  • The createStudent function allows us to create multiple student objects with different properties by simply calling the function with different arguments.
  • This method of using new Object() is particularly useful when working with dynamic data or when you need to create multiple similar objects.

When JavaScript starts sprinting, but you’re just trying to keep up — stay with me, we’re almost there!

3. Accessing and Modifying Object Properties
Once you’ve created an object, either using the object literal or new Object() syntax, you can easily access and modify its properties using dot notation or bracket notation.

Another great thing about JavaScript objects is that they are highly flexible. You can delete or remove a property from an object, add new properties or update existing ones at any time after the object has been created. If you need to remove a property from an object, you can use the delete keyword:

delete student. Grade;
Enter fullscreen mode Exit fullscreen mode

Why It Matters

Understanding how to create and manipulate objects using both object literal notation and the new Object() syntax is more than just a coding skill—it’s a foundational aspect of working with JavaScript.

  • Organizing Your Code

Objects in JavaScript are like the organizational backbone of your code. Imagine you’re managing a large project, whether it’s a website, an app, or even a simple game. Each piece of data you handle — whether it’s user profiles, product details, or game characters — needs to be stored and accessed efficiently. Objects provide a way to group related data and functions together, making your code more intuitive and easier to navigate.

For instance, if you’re building an online store, you might have objects representing each product, each customer, or even each order. These objects can hold all the relevant data, like product prices, customer names, or order statuses, in one neat package. This not only keeps your code organized but also makes it much easier to manage and update as your project grows.

  • Flexibility and Scalability

As your application becomes more complex, the ability to scale effectively is crucial. Objects offer a flexible structure that can be easily expanded. Need to add new features? Simply extend your existing objects with new properties or methods. Want to update how certain data is processed? Modify the methods within your objects without disrupting the entire codebase.

This scalability is particularly important in large applications where maintaining clean and modular code can be the difference between a manageable project and a chaotic one. By organizing your code into well-structured objects, you ensure that your application can grow and evolve without becoming unwieldy.

  • Reusability and Efficiency

Another key benefit of using objects is reusability. Once you’ve created an object blueprint, you can use it repeatedly throughout your application. This means you can avoid duplicating code, which not only saves time but also reduces the chances of errors. For example, if you have a User object that defines how user data should be structured and accessed, you can create multiple user instances without having to rewrite the same code over and over.

Moreover, objects make it easier to implement design patterns that promote code efficiency, such as the Singleton pattern (where you ensure a class has only one instance) or the Factory pattern (where you create objects without specifying the exact class of the object that will be created). These patterns rely heavily on the flexibility and structure that objects provide.

  • Mastering JavaScript

Finally, mastering object creation and manipulation is a stepping stone to becoming proficient in JavaScript. Many advanced JavaScript concepts, like prototypal inheritance and classes, build upon a solid understanding of objects. Whether you’re debugging, optimizing, or refactoring code, knowing how to work with objects will make these tasks more manageable.

As you continue to develop your skills, you’ll find that objects are not just another feature of JavaScript — they are central to how the language operates. By mastering these techniques, you’ll be equipped to write cleaner, more organized, and more powerful code, setting you on the path to becoming a proficient JavaScript developer. With the basics of object creation under your belt, you’re well on your way to unlocking the full potential of JavaScript, ready to tackle complex challenges with confidence.

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Dot notation cannot be used if the object key is a Symbol 👍