DEV Community

Cover image for Unpacking the JavaScript Junk Drawer: The Marvels & Mayhem of Objects 🗃️
Aniket Botre
Aniket Botre

Posted on

Unpacking the JavaScript Junk Drawer: The Marvels & Mayhem of Objects 🗃️

Greetings, JavaScript enthusiasts and aspiring coders! Ever encountered code that looked like a mess? Worry not, because JavaScript objects are here to help!


The Lowdown on JavaScript Objects

JavaScript objects are fundamental constructs that allow you to store collections of key-value pairs. They are similar to real-life objects in that they are standalone entities with their own properties and methods. In JavaScript, objects can contain many values, unlike primitive data types such as numbers or strings. These values can be of various types, including other objects, functions, and primitive data types.

Creating Objects

There are several ways to create objects in JavaScript:

  • Object Literal: The most common approach, using curly braces {} to enclose key-value pairs separated by commas.
const person = {
    firstName: "Alice",
    lastName: "Smith",
    age: 30,
    greet: function() {
        console.log("Hello, my name is " + this.firstName + " " + this.lastName);
    }
};
Enter fullscreen mode Exit fullscreen mode
  • new keyword: While less common for simple objects, the new keyword can be used with a constructor function (a function designed to create objects).
function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
    this.drive = function() {
        console.log("Vroom! The " + this.make + " " + this.model + " is on the road!");
    };
}

const myCar = new Car("Ford", "Mustang", 2023);
Enter fullscreen mode Exit fullscreen mode
  • Other Methods: Less frequently used methods include Object.create(), Object.assign(), and Object.fromEntries().

Properties and Methods

  • Properties: These are named values that represent characteristics or attributes of the object. They can be accessed using dot notation obj.propertyName or bracket notation obj["propertyName"].

  • Methods: Functions defined within objects are called methods, and they represent actions that an object can perform.

let person = {
    name: "John",
    age: 30,
    greet: function() {
        console.log("Hello, " + this.name);
    }
};

person.greet(); // Output: Hello, John
Enter fullscreen mode Exit fullscreen mode

Objects love to accessorize with properties. Here's how you can give your object some style:

let user = {
  name: "John", 
  age: 30
};
Enter fullscreen mode Exit fullscreen mode

Imagine user as a filing cabinet, and name and age as drawers labeled accordingly. Need to fetch John's age for a surprise birthday party? Just use the trusty dot notation:

alert(user.age); // Party planning made easy!
Enter fullscreen mode Exit fullscreen mode

Advanced Object Features

  • Nested Objects: An object can include another object as a property, which is known as a nested object.

  • Pass by Reference: Objects are passed by reference, meaning that when you assign an object to a variable, you are passing a reference to the same memory location.

  • Checking Property Existence: You can check if a property exists using the in operator, hasOwnProperty method, or optional chaining operator ?.

  • Iterating Over Properties: The for...in loop is used to iterate over the properties of an object.

  • Object Destructuring: This feature allows you to extract properties from an object and assign them to variables.

  • Spread Operator: The spread operator ... can be used to copy properties from one object to another.

  • Object.assign(): This method is used to copy properties from one object to another.

We will be covering more about objects in JavaScript in upcoming blogs.


Wrapping Up: The Cabinet of Curiosities

JavaScript objects are like a cabinet of curiosities. They hold an array of fascinating and useful features, ready to be explored. Whether you’re just starting out or you’re a seasoned coder, understanding objects is crucial in navigating the vast ocean of JavaScript.

So, next time you dive into JavaScript, remember: objects are your best friends (or frenemies, on a bad day). They’re complex, powerful, and sometimes a tad bit overwhelming, but they’re the building blocks of just about everything in JavaScript.

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Objects are passed by reference

This is incorrect, or at least not explained well. JavaScript does not have pass by reference. Everything passed to a function is passed by value. In the case of Objects (and other non-primitives) - that value just happens to be a reference.

If JS did have pass by reference (with objects or otherwise) you'd be able to change the value of a variable inside a function, but you can't:

let myObj = { a: 123 }

function changeTheObject(a) {
  a = { b: 456 }
}

console.log(myObj)   // { a: 123 }
changeTheObject(myObj)
console.log(myObj)   // { a: 123 } - it didn't change
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aniket_botre profile image
Aniket Botre

Yeah I thought of it, but when I researched about it I found out this...

Primitives are passed by value, and Objects are passed by "copy of a reference".

Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, and it is possible to modify the contents of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller - i.e. the reference itself is passed by value:

function replace(ref) {
    ref = {};           // this code does _not_ affect the object passed
}

function update(ref) {
    ref.key = 'newvalue';  // this code _does_ affect the _contents_ of the object
}

var a = { key: 'value' };
replace(a);  // a still has its original value - it's unmodfied
update(a);   // the _contents_ of 'a' are changed
Enter fullscreen mode Exit fullscreen mode

Stackoverflow URL

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Yup, so it's not 'pass by reference' - the value being passed is a 'copy of a reference'.

From the original answer page linked from that StackOverflow page, we see this (emphasis mine):

Instead, the situation is that the item passed in is passed by value. But the item that is passed by value is itself a reference. Technically, this is called call-by-sharing.

Thread Thread
 
aniket_botre profile image
Aniket Botre

Ooh I see. Thanks for the clarification!