2

JavaScript keeps surprising me, or I'm just rushing. lol

class Group {
#group;

constructor(){
this.group = [];
return this.group;
}

add(item) {
// only if it isn't already a member
// value can be part of set only once
if(!this.has(item)) {
group.push(item);
}
}

has(item){
// return boolean: item member of group
for(let i=0; i<group.length; i++) {
if(group[i] === item) {
return true;
}
}
return false;
}

let group = new Group();
group.add(1);
console.log(group);

Error: group.add() is not a function
Why is group.add() not a function?
A.I. analysis:

1. Private field vs public field:
A private field #group can only be accessed as this.#group. But in the constructor, I wrote:
this.group = [];

This creates a new public field, unrelated to #group.

2. Returning from constructor:
return this.group;

In JavaScript, a constructor automatically returns this, which is the instance of the class. Returning this.group replaces the instance with the array. That’s why after new Group(), your variable group is just an array, not an instance of Group. Arrays don’t have the add method — hence the error.

3. Referencing group inside methods:
group.push(item);
Here group is not defined. You probably meant this.group (or this.#group if using the private field).

Note to self: in the magic of computer science, you must be precise. If I loosely define the black box, the result will have a chance of producing anomalies.. kind of like reality. lol

Comments
  • 0
    idk if that private does anything

    also that's confusing to read

    oh how I miss js but not that if() syntax. rust omits () and returns can be made without return keyword also. js dynamic variables tho
  • 0
    @jestdotty I know. JS also allows the omission of (), {} and return but I rather keep it for clarity, as keeping a multi-line if body in one line can introduce bugs.
  • 1
    @princess Please analyze this rant.
  • 2
    Tell me that you're used to C# without telling me you did C#.
Add Comment