0

what does it means declare variables with the symbol "#" in javascript? I am learning about builder pattern and I found it with some examples. Also I saw that the variables are calls with this.#color.

# symbol is different to declare variable with let or var? what is the difference?

thanks

class Car {

    #color = null
    #spoiler = null
    #fuelType = null
    #productionDate = null

}
Reporter
  • 3,897
  • 5
  • 33
  • 47
estudiante
  • 45
  • 5
  • It marks the fields as private: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields – Rory McCrossan Nov 22 '22 at 14:41

2 Answers2

4

Private class members

class ClassWithPrivate {
  #privateField;
  #privateFieldWithInitializer = 42;

  #privateMethod() {
    // …
  }

  static #privateStaticField;
  static #privateStaticFieldWithInitializer = 42;

  static #privateStaticMethod() {
    // …
  }
}
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
0

It means private variable.

class Car{
    #color = "#FFF";
    // a getter to read the value
    get color() { return this.color; }
}

If you try to affect the private variable from outside of this class it will fail including passing a method inside this class to another system. I will say that debuggers such as the browser's console is still able to see these values for debugging.

E.G

class Car{
    #color = "#FFF";
    // a getter to read the value
    get color() { return this.color; }

    #setColor = (color) => {this.#color = color}
    
    passColorSetter = (fn) => {
        fn(this.#setColor); // this is not allowed 
        // as the referenced function in fn is not defined in this class
    }
}

So they are truly private unlike the hacks that used to exist E.G

function Car{
    let color = "#FFF";
    this.getColor = function(){ return color; }

    let setColor = (c) => {color = c}
    
    passColorSetter = (fn) => {
        fn(setColor); // this would work
        // and allow the fn referenced function to call setColor
    }

}
Barkermn01
  • 6,781
  • 33
  • 83