What is the function of the underscore in objects?


#1

This is more of a general concern: when exactly is the underscore _ used before a property? Does it alter the code or just a way for us to notice it and not change the value?

In exercise Getters and Setters 3, when I used console.log on the last line, I initially use console.log(person._age) but the program says it is incorrect; but the effect is apparently the same. So when exactly is the underscore used?
https://www.codecademy.com/courses/learn-javascript-objects/lessons/objects/exercises/getters-setters-iii?action=lesson_resume&course_redirect=introduction-to-javascript


let person = {
  _name: 'Lu Xun',
  _age: 137,
  
  get age() {console.log(`${this._name} is ${this._age} years old.`); return this._age;
            }
};

console.log(person.age)

#2

yes, its only a naming convention to remind us (programmers) that this properties use getters and setters


#3

So it means for the last line of code if I had written console.log(person._age it will not make a difference?


#4

it will indeed not make a difference, we can still access and modify the property directly. But we shouldn’t, that is why we add the underscore, to remind ourselves that we should use getters and setters for this property.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.