Magdi Gamal
Magdi Gamal

Reputation: 678

Is there a point, besides organization, of using object properties instead of variables?

I've only been using for a month so sorry if this is a dumb question, but are there actually any practical benefits of for example saying

var object = {
  x: x,
  y: y,
  z: z
}

instead of simply declaring the value as variables

var x = x, y = y, z = z;

Upvotes: 0

Views: 32

Answers (1)

Sam R
Sam R

Reputation: 702

Objects first come in handy when you want to organize elements together.

If you are working with a location in space, you can create a point that keeps x, y, and z together:

var point = {
  x: 0,
  y: 1,
  z: -2
};

// Move
point.x += 1;

Now you have one object (point) that tells you a little about itself. You don't have to remember which things go together to make up your point, because they are together on the object.

They become even more important when you start working with arrays of these objects, which people sometimes refer to as collections (though not everyone).

var ships = [];
// Add some points to the array
ships.push(point1);
ships.push(point2);

Now each "ship" in the collection has it's own x, y, and z.

There are plenty of places where it makes sense to use a var instead of an object property. Most of these are inside a function, where you need to hold onto a value for a little while, and don't need other people to know about it.

Upvotes: 1

Related Questions