Understanding Objects in JavaScript

Understanding Objects in JavaScript

·

5 min read

Learning javascript involves two key concepts- Objects and Events. In this article , we will discuss everything that will help you lay a solid foundation on Objects.


Objects - Key: Value Pairs

If you had any previous programming language experience you would have read a data structure such as hashmap /dictionary which stores its element in the form of < key> : < value > like this

{ a: ‘3 ‘ , ‘b’: 2 , ‘c’ : 10 }

Similar to that Objects are in javascript are stored something like this :

You can store anything as a value in a key-value pair inside an object.

const obj = {
    name: "Raghav",       // String 
    age: 20,              // Number 
    isStudent: true,      // Boolean 
    hobbies: ["Music", "Coding"],  // Array 
    address: {            // Object 
        city: "Bangalore",
        country: "India"
    },
    greet: function() {   // Function 
        console.log("Hello!");
    }
};

Note:

  • Instead of writing greet: function() { console.log("Hello!");}

    We can write it as greet () { console.log("Hello!"); }

  • Though value can be anything , keys must only be strings or symbols .


There are two methods of accessing the property value of an object in JS

  • Dot notation - <Object>.<Property>

  • Bracket notation - <Object>[“<Property>”]

const person = { name: "Raghav" };

console.log(person.name);  //  Output: "Raghav"
console.log(person["name"]);  //  Output: "Raghav"

How It Is Stored Internally (as key-value pairs)

In the backend , these property keys are actually stored as strings .

{
    "name": "Raghav",       
    "age": 20,             
    "isStudent": true,     
    "hobbies": ["Music", "Coding"],  
    "address": {            
        "city": "Bangalore",
        "country": "India"
    },
    "greet": function() { 
        console.log("Hello!");
    }

Points to Remember regarding accessing the property values

  • If the key is written normally (without quotes) , JavaScript automatically converts it into a string (Except Symbols)

      const obj = { 1: "One", 2: "Two" };
    
      console.log(obj["1"]); // "One" ✅
      console.log(obj[1]);   // "One" ✅ (Same as obj["1"])
      console.log(obj.1); //"Error" dot notation wont work for numeric keys
    

If the key itself is already a string, you can only access it using bracket notation ([]) , dot notation would fail ❌

const obj = { "first-name": "Raghav" };

console.log(obj["first-name"]); // "Raghav" ✅
console.log(obj.first-name);    // NaN ❌

Everything in JS is Objects

Yes you heard it right , almost everything you work with is an object such as arrays and functions.

Arrays in JavaScript are special objects where keys are automatically set as numbers (0, 1, 2,...). It is indexed form of Objects.

const arr = ["a", "b", "c"];
console.log(typeof arr); // "object"
console.log(a[0]) // "a"
console.log(a["0"]) // "a"

Internally, it looks like this:

 {
    0: "a",
    1: "b",
    2: "c ",
    length: 3
};

That is why we are able to directly access arr.length, which dynamically updates as elements are added or removed.

Similarly in functions , we store values using the dot notations ( similar to objects)

function greet() { 
    console.log("Hello!");
}

// Adding a property to the function
greet.name = "Raghav";
console.log(typeof greet); //function ( But still internally it works like an object)
console.log(greet.name); //Raghav

Internally , it looks something like this :

greet = {
    [[FunctionCode]]: function() { console.log("Hello!"); },
    name: "Raghav"
};

Even Primitives (such as strings,numbers,boolean) are temporarily wrapped in wrapper objects when accessing properties.

console.log("Raghav".length); // ✅ 6 (String is temporarily wrapped in a String object)

Object Utility Methods:

Object utility methods are methods on the Object class that help in working with objects. They do not require an instance and can be used directly on any object. (we externally apply it)

Let’s say we have an object called user, which is an instance (example)of the Object class:

const user = { name: "John", age: 25 };
  • If we use user.<any method>, it won't be a utility method because we are directly applying it on the instance of the class Object.

  • If a method is called as Object.method(user), it is a utility method because it is working externally through the Object class

  1. Object.keys(obj) → Returns an array of keys.

  2. Object.values(obj) → Returns an array of values.

  3. Object.entries(obj) → Returns key-value pairs as arrays.

  4. delete obj.key → Removes a property from an object.

const user = { name: "Raghav", age: 20, city: "Bangalore" };
console.log(Object.keys(user));    // ["name", "age", "city"]
console.log(Object.values(user));  // ["Raghav", 20, "Bangalore"]
console.log(Object.entries(user)); // [["name", "Raghav"], ["age", 20], ["city", "Bangalore"]]
delete user.age;
console.log(user.age)//undefined 
console.log(user); // { name: "Raghav", city: "Bangalore" }

Now we can apply array methods like push(), pop(), or length on them.


How to check if a property is present in an object

There are multiple ways of doing this,

  • hasOwnProperty()

  • "key" in object

  • object.key

Each of these methods is used in different scenarios. First of all, remember that a property in an object can either be inherited or direct.

  • If a property is inherited, it comes from the prototype and is called a prototype property.

  • If a property is directly declared inside the object, it is called a direct property.

Comparison Table

MethodChecks Direct Property?Checks Prototype Property?Returns
x.hasOwnProperty("password")✅ Yes❌ Notrue or false based upon existence [Boolean]
"password" in x✅ Yes✅ Yestrue or false based upon existence[Boolean]
x.password✅ Yes✅ YesValue or undefined [Value]
const obj = { name: "Raghav" };
// Direct property check
console.log(obj.hasOwnProperty("name")); // true ✅
// Checks both direct and inherited properties
console.log("name" in obj); // true  ✅
// Accessing property value
console.log(obj.name); // "Raghav" ✅

When checking if an object property exists before deleting it, using if (x.password) can lead to unexpected results in cases where the value of x.password is falsy (like an empty string, "" or 0 or null).

Example Scenario

Let's say we have a user object and we want to delete password if its exists ,assume here the password is a empty string (which can valid✅)

const user = { 
    name: "Raghav", 
    password: ""  // The password exists but is an empty string
};

if (user.password) {  // user.password leads to " " ...if("") converts it to 0  so the condition is set to false
    delete user.password;
}

console.log(user); // { name: "Raghav", password: "" } ❌ (Password was NOT deleted)

Thankyou!!