Investigate objects

Objects are at the center of almost everything in JavaScript. It's best we understand exactly what they are and how we use them.

Accessing an object's contents

If we can put things inside these structures, how do we access them again? Write the code to access each property and log it to the console.

šŸ¤”

We know we can get the length of an array. Can we get the length of an object? Why / Why not?

How different are the rules for arrays?

You've probably heard many times that arrays are zero indexed, starting with 0. If that's the case, we should only be able to use numbers to access their contents, right? Will the code below work?

What about giving a value a different index?

Let's switch the index for 2 values in an array? Do the other indexes change too or just the index for that value?

Accessing nested objects and arrays

Objects, arrays and functions behave differently to primitives.

Take this example:

  const staff = [
    {
      name: 'Alex',
      job: {
        title: 'Filing Clerk',
      }
    },
    {
      name: 'Humeira',
      job: {
        title: 'Engineer'
      }
    }
  ];

Alex, currently a Filing Clerk, successfully career transitions and is awarded the same job as Humeria, an Engineer. Let's see that in code:

That seems to have worked šŸŽ‰.

In the meantime, Humeira applied for a new position and is awarded the role of Senior Engineer.

That code change is simple enough:

  staff[1].job.title = 'Senior Engineer';

Do you see any problems yet? Let's run the code below, which prints the roles of each staff member.

Wait, what? Alex is now a Senior Engineer now too?

What do you think went wrong? What are the fundamentals here that were missed? šŸ¤”

Can two objects ever be exactly the same?

In JavaScript, whenever we are comparing values, we are talking about EQUALITY.

Remember that strict teacher's cane 🦯 === ?

Let's compare two empty objects using this method. No coercion here.

If that wasn't the answer you were expecting, what about this?

So objects clearly behave differently to primitives. Let's explore why šŸ•µļø