Skip to main content

Building Blocks in JS

Objects - Part 2

Let's do a quick recap about what objects are first!

An object is a non-primitive datatype in javascript. Objects store data in a key-value pair format, where a value can be of any data type again and nested to "n" levels.

Objects can be created with {...} brackets. It can take in key-value pairs inside of it, where the key is generally termed as properties.

Objects can also be created using the new keyword as const obj = new Object();

In the previous article, we also discussed accessing object properties, object properties can be accessed in two ways

  1. Using the dot notation
console.log(person.name); // Shrikanth
console.log(person.age); // 28

or the other way to access the properties would be using the square bracket notation such as

console.log(person["name"]); // Shrikanth
console.log(person["age"]); // 28

We also discussed that we can add or remove a property to an object using the same dot and square bracket notation.

Then we went on to discuss how we can add dynamic properties to an object. All of this is discussed in detail in this article.

Now let us discuss Computed Properties!

Computed properties

When creating an object properties, we learnt that there are two ways.

One - is the dot notation way and the second is the square bracket way. We also learned that we can take property names on the fly, from a variable or from a user input right? These, being used inside of the object, are called computed properties.

let color = prompt("Which colored bag do you want to buy?", "red");

let bag = {
  [color]: 2, // The color name is taken from the variable color
};

alert( bag.red ); // This will equal to 2

The meaning of computed property here means that the color variable itself won't be the property name but instead the value it holds becomes the property name.

the resulting object will look like

{
  red: 2
};

But if you use it without the square brackets, it will take the string as the value

The resulting object will not be what we expect instead will be

{
  color: 2
};

Hence do not forget the [...] brackets!

You can even add an expression inside of the square brackets depending on our use case like:

let color = prompt("Which colored bag do you want to buy?", "red");

let bag = {
  [color + "Gucci"]: 2, // The color name is taken from the variable color
};

alert( bag.red ); // This will equal to 2

Now the property will be redGucci . That is how we create property names on the fly. This comes in handy a lot when you are working with objects. More often than not we do need to set property names either from a dynamic API call or some other calculation within the client-side code. This is a handy tool to remember.

Property value shorthand

When we code in real time, we generate such objects inside the functions and return them, and then we sometimes need to use the property name dynamically off of the variables.

This makes life very simple for us. This is extremely useful.

Assignment: Now try creating a couple of objects yourself using the computed property way and the property shorthand way.

But wait, the property "name" - the value is the same thing here right - "name" and "age". So the result would be

{
name: "Shrikanth",
age: "28",
};

Hence there is a shorthand, they know that you don't like writing repetitive code, hence you could just write:

function createPerson(name, age) {
  return {
    name,
    age,
  };
}

let user = makeUser("Shrikanth", 28);
console.log(user.name); // Shrikanth

This would work just the same! Isn't this much simpler?

Property name limitations

First things first, let's talk about property names. Remember how we have certail rules like you won't name a new born baby "1" or "car", Well, in the world of JavaScript objects, you can name properties almost anything you want!

let meriDukaan = {
  for: "Chai",
  let: "Samosa",
  return: "Jalebi"
};

console.log(meriDukaan.for + " ke saath " + meriDukaan.let + " aur " + meriDukaan.return);
// Output: "Chai ke saath Samosa aur Jalebi"

See that? We just used reserved words like for, let, and return as property names. JavaScript doesn't bat an eyelid! It's like wearing mismatched socks - unconventional, but totally allowed.

let diwaliMenu = {
  0: "Kaju Katli",
  1: "Besan Ladoo",
  2: "Gulab Jamun"
};

console.log(diwaliMenu[0]); // "Kaju Katli"
console.log(diwaliMenu["0"]); // Also "Kaju Katli"

Javascript automatically converts the number to a string. So 0 and "0" are treated the same way. It's like calling your friend "Rahul" or "Dear Friend" - same person, different name!

Proto

let obj = {};
obj.__proto__ = 5; // Trying to assign a number
console.log(obj.__proto__); // [object Object] - Arre yaar, it didn't work!

See that? __proto__ is stubborn. It refuses to be anything but an object. It's like trying to convince your mom that pizza is a vegetable - it's just not going to happen!

"Does This Property Exist?"

Now, let's play detective! How do we know if an object has a certain property? It's easier than finding out who ate the last piece of cake (it was you, wasn't it?).

Method 1: The Undefined Check

let biryani = {
  type: "Hyderabadi",
  spiceLevel: "High"
};

console.log(biryani.price === undefined); // true, because price doesn't exist

This works, but it's not foolproof. It's like asking, "Is anyone home?" when the lights are off. Sometimes, people are home but sitting in the dark!

Method 2: The "in" Operator

let biryani = {
  type: "Hyderabadi",
  spiceLevel: "High"
};

console.log("type" in biryani); // true
console.log("price" in biryani); // false

The in operator is like that nosy neighbor who always knows what's going on. It'll tell you for sure if a property exists, even if it's hiding!

Looping Through Properties

Now, what if we want to see all the properties of an object? It's like wanting to taste every dish at a wedding buffet. For this, we use the for...in loop:

let thali = {
  mainCourse: "Dal Makhani",
  bread: "Naan",
  sideDish: "Paneer Tikka",
  dessert: "Rasmalai"
};

for (let item in thali) {
  console.log(item + ": " + thali[item]);
}

This loop is like a food tour guide, showing you every delicious item in your thali!

The Mystery of Object Order:

Now, here's where things get as twisted as a Bollywood plot. The order of properties in an object isn't always what you expect. It's like standing in a line for movie tickets - sometimes there's a logic, sometimes it's chaos!

For properties with integer names (or strings that look like integers), JavaScript sorts them:

let phoneCode = {
  "91": "India",
  "1": "USA",
  "44": "UK",
  "81": "Japan"
};

for (let code in phoneCode) {
  console.log(code); // "1", "44", "81", "91"
}

See that? It's sorted! It's like arranging your spice box in order - the small numbers come first.

But for non-integer properties, it's first come, first served:

let cricketTeam = {
  captain: "Virat",
  viceCaptain: "Rohit",
  wicketKeeper: "Dhoni"
};

cricketTeam.coach = "Dravid";

for (let role in cricketTeam) {
  console.log(role); // captain, viceCaptain, wicketKeeper, coach
}

Here, the properties appear in the order they were added. It's like friends joining you for a movie - they sit in the order they arrive.

The Great Property Order Hack

But what if you want to control the order, like arranging your favorite snacks in order of preference? Here is a hack

let phoneCode = {
  "+91": "India",
  "+1": "USA",
  "+44": "UK",
  "+81": "Japan"
};

for (let code in phoneCode) {
  console.log(code); // "+91", "+1", "+44", "+81"
}

By adding a "+" before the numbers, we've turned them into strings that don't look like integers to JavaScript. Now they'll appear in the order we added them. It's like adding a pinch of masala to change the entire flavor of the dish!

Wrapping Up

So there you have it, folks! We have learned JavaScript object properties. We've seen how flexible they can be with names, how to check if they exist, how to loop through them, and even the quirky way they get ordered.

Remember:

  1. Property names are like nicknames - almost anything goes!
  2. Use the in operator to check for property existence
  3. for...in is your tour guide through the object.
  4. Property order can be tricky - integers get sorted, and others stay in creation order.
  5. And if you want to control the order, just add a little spice (like "+") to your property names!

That's it!