Is naming a var after a property bad practice?


#1

Hello everyone,

In Accessing Properties, Part 2 we are instructed to assign properties to variables with matching names (see below).

If I understand correctly, I believe the property names don't have scope outside of the object (perhaps scope does not even apply? Do properties behave like variables?) Either way, it seems to me that they are cannot be confused with each other by the program(?).

But on the human side of things, I was wondering if this is a good practice or not (disclaimer: I was confused by the exercise because of this; sub-disclaimer: on the other hand we've had yet to deal with objects in this way).

Is it conventional to assign properties to variables with matching names? Is it a practice best avoided? Your input would be greatly appreciated.

Thanks all,
I'm not a robot I swear


https://www.codecademy.com/courses/spencer-sandbox/1/4?curriculum_id=506324b3a7dffd00020bf661#


// Take a look at our next example object, a dog
var dog = {
  species: "greyhound",
  weight: 60,
  age: 4
};

var species = dog["species"];
// fill in the code to save the weight and age using bracket notation
var weight = dog["weight"];
var age = dog["age"];


#2

I can understand the confusion for someone who has just started to tackle objects in this way, but as you say, the scope for the object properties (species, weight and age) are restricted in such a way that the program at least would not have trouble executing.

I don't think there is a particular convention when it comes to duplicate names between object properties and those outside its scope. I think as time goes on you'll learn to differentiate between the two without really thinking. But if you disagree, there's nothing wrong with using different names.

There're so many general programming conventions when it comes to naming. Regardless of what you do, the most important thing to remember is just to be consistent.


Naming var after prop'ty pt II: naming key after method
#3

Hi @nedwards,

Thank you for your help and guidance. Indeed, seeing this for the first time made me feel a bit cross-eyed!

If I may follow up with a question in regards to 'This' Works for Everyone... (I think there's some overlap here and wasn't sure whether it's preferable for me to spin off into a new thread or...).

Edit: I found the "linked topic" button so I moved my question there).