0

In javascript, objects are considered as variables(At least according to my knowledge).

ex:

var myCar = new Object();
myCar.make = 'Ford';
myCar.model = 'Mustang';
myCar.year = 1969;

I do not understand the logic behind this. Can this be true even in languages like c++(i.e can C++ objects be considered as variables)?

2 Answers 2

4

Technically the myCar that you created is a variable which stores the instance of the object that you created using new Object().

Variables are like a box where in you can store specific data and access it along your code.

So variables can come in many shape or form depending on what data you put on it. It can come as a string, objects, array, number or boolean.. It does not always have to be an object.

Sign up to request clarification or add additional context in comments.

Comments

1

I think you're confusing several concepts here. A "variable" is a way of referring to an object, and in languages like JavaScript, a way of retaining a reference to it so it doesn't go away until you're done with it.

In C++ there are also variables, but they're more as a convenience to the programmer as once that code is compiled they don't exist in the same fashion as they do in JavaScript, they can often get optimized away.

In your code you have a variable myCar which lets you manipulate the object. If you just did this:

new Object()

That creates an object, but effectively throws it away. In JavaScript this gets garbage collected and cleaned up. In C++ that's a memory leak.

You can have objects without variables, and you can have variables without objects, like this:

var x = 9
console.log(typeof(x))
// => number

Where x is a variable and it's just a number, not an object.

Saying "objects are considered variables" is like saying "a house can be considered its street address". It's not true though. It's a building that happens to have a particular street address, but you can move the house around, and some houses even have wheels on them for this purpose. Likewise, addresses can change but the house remains the same.

A street address is a way to refer to a house, just as a variable can refer to an object. It could also refer to an empty lot, as undefined in JavaScript.

Tip: It's generally a good practice to use let or const now instead of the more generic, and sometimes troublesome var.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.