0

I'm learning the Codecademy Advanced JavaScript course, I'm learning about classes.

In their code, I feel this.variable and this._variable have no different but they require to write this.variable even though 2 options return the same output.

Can you please explain the differences if you understand this?

These are some examples of code

class Dog {
  constructor(name) {
    this._name = name
  }
}

Is it different from:

class Dog {
  constructor(name) {
    this.name = name
  }
}
Oscar Nguyen
  • 43
  • 1
  • 9

2 Answers2

1

**

1.Names can contain letters, digits, underscores, and dollar signs. 2.Names must begin with a letter Names can also begin with $ and _ 3.Names are case sensitive(y and Y are different variables)

**

  • i've added some code. you can check it. – Oscar Nguyen Jan 13 '22 at 08:14
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 13 '22 at 10:35
1

Define variables preceded by an underscore is just a convention to mark them as private, but javascript doesn't support encapsulation so this is only for helping the developer identify private variables.

In this post you have a similar question: Is the underscore prefix for property and method names merely a convention?

adrisons
  • 3,443
  • 3
  • 32
  • 48
  • Yes it does? https://medium.com/javascript-scene/encapsulation-in-javascript-26be60e325b4 – evolutionxbox Jan 14 '22 at 10:41
  • Well, you can simulate it with clousures and scopes, but I meant encapsulation based on the variable definition (like in java you have private, protected or public) – adrisons Jan 14 '22 at 11:07
  • 1
    We now do have some [private fields](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields) in JS. I'm not sure if they're based on closures, though. – Teemu Jan 14 '22 at 12:48
  • Didn't know about that, thanks @Teemu – adrisons Jan 14 '22 at 12:54