I need some help with JavaScript Classes

I was practcing Classes in JavaSctipt using the Practice Pack and I’m a bit lost as to what is wrong in my code.

The link to what I am talking is:
https://www.codecademy.com/practice/paths/web-development/tracks/webdev-intermediate-javascript/modules/errors-and-error-handling

The question is:

Q: Define a class named Employee .

Your class should have a constructor function that takes in an employee’s name and hourlyWage and sets them as properties with those names. An hoursWorked property should be initialized to 0 .

The Employee class should have a logHours() function that takes in a number of hours worked and increments the hoursWorked property by that amount.

The Employee class should have a generatePaycheck() function that logs to the console the hoursWorked multiplied by the hourlyWage . It should then set the hoursWorked to 0 .

What I did was:


// Define your class below:

class Employee{

  constructor(name,hourlyWage,hoursWorked){

    this.name = name;

    this.hourlyWage = hourlyWage;

    this.hoursWorked = 0;

    }

    get name(){

      return this._name;

    }

    set name(newName){

      this._name = newName;

    }

    get hourlyWage(){

      return this._hourlyWage;

    }

    set hourlyWage(newHourlyWage){

      this._hourlyWage = newHourlyWage;

    }

    get hoursWorked(){

      return this._hoursWorked;

    }

    loghours(numHoursWorked){

      return this._hoursWorked += numHoursWorked;

    } 

    generatePaycheck(hoursWorked,hourlyWorked){

      var totalPay = this._hoursWorked * this._hourlyWorked;

      console.log(totalPay);

      this._hoursWorked = 0 

    }

};

I am fairly new to programming and JavaScript and have been trying to figure out what I did wrong. Please help! :slight_smile:

Welcome to the forums :slight_smile: !

It’s pretty good! Classes and OOP are no joke.

Two things I can see being an issue in the code is that you almost have getters/setters for everything, except for one attribute. That’ll throw an error.

The other has to do with standard syntax, and won’t throw an error in a compiler, but is a good thing to watch out for (and the CC validator will throw an error probably):

My clue is this line:

The Employee class should have a logHours() function

Check to see whether you followed this properly.

3 Likes

Funny timing as I too am struggling to understand if I’m on the right path (no error messages thus far) because it’s not clear when one is complete :white_check_mark: with this practice question.

The Employee class should have a generatePaycheck() function that logs to the console the hoursWorked multiplied by the hourlyWage . It should then set the hoursWorked to 0 .
Does this mean a setter should be set to zero on hoursWorked?

class Employee {
  constructor(name, hourlyWage, hoursWorked ) {
    this._name = name;
    this._hourlyWage = hourlyWage;
   this._hoursWorked = 0
  }
  logHours(hoursWorked){
    hoursWorked++
  }
generatePaycheck(){
 console.log(this._hourlyWage * this._hoursWorked );

} 
get name() {
  return this._name = name;
}
get hourlyWage() {
  return this._hourlyWage = hourlyWage;
}
get hoursWorked() {
  return this._hoursWorked 
}

set name(stafferName){
  this._name = stafferName;
}

set hourlyWage(wages){
  this._hourlyWage = wages;
}
set hoursWorked(hoursofWork){
  this._hoursWorked = hoursofWork;
}
}

After hitting Run then Continue just to 'test" and see where I stand the following message showed up:

We invoked new Employee() with "Alex" as the first argument and expected the returned object to have the property .name equal to "Alex" but instead it was undefined

THen I hit continue to see if there is more instructions and I am forwarded to this next question in the Practice Pack.

So I am confused. I’m not clear when new instructions asking us to create a new instance of Employee named Alex was asked of us? Does this message indicate I (we) are on the right path?

Thanks @course0615120881 @toastedpitabread for the widsom and helping me borrow some code…

Nathan

We invoked new Employee() with "Alex" as the first argument and expected the returned object to have the property .name equal to "Alex" but instead it was undefined

Usually the validator runs some tests on your code to see how well it runs, the test could have been something like this:

alex = new Employee("Alex", 40)
console.log(alex)

It means that something wasn’t working in regards to have the name come out properly when alex is logged possibly.

Thank @toastedpitabread kindly for the quick response. I’ll loop back to the Classes Practice Pack shortly and revisit this question with the code you’ve passed on. I’ve moved onto the next project but I appreciate this simple method to confirm if name and hours are being passed through (if I’m saying that correctly?).

Hello again!

Thanks for your prompt reply! I managed to solve it :slight_smile:

I am also having trouble with this problem, but from the Classes Practice Pack. I am getting a response that says:
" The generatePaycheck() function should logs to the console the hoursWorked multiplied by the hourlyWage . It should then set the hoursWorked to 0 ."
I have been messing with it a bunch on my own and am no closer to figuring it out. Can anyone give me a hand?
p.s. I really wish there were solutions, test results, or really any info whatsoever to help us figure these things out on our own.

// Define your class below:

class Employee {
  constructor(name, hourlyWage) {
    this._name = name;
    this._hourlyWage = hourlyWage;
    this._hoursWorked = 0;
  }

  get name() {
    return this._name;
  }
  get hourlyWage() {
    return this._hourlyWage;
  }
  get hoursWorked() {
    return this._hoursWorked;
  }
  set hoursWorked(hoursWorked) {
    this._hoursWorked = hoursWorked
  }

  logHours (num) {
    this._hoursWorked += num;
  }

  generatePaycheck() {
  let payCheck = this._hoursWorked * this._hourlyWage;
  return console.log(payCheck);
  hoursWorked = 0;
  }
  
};

Hello, @virtual.jess. Consider what return does. It sends a value, and control flow back to the line of code that called the function. Code following a return statement that is executed is unreachable. If you consider what the exercise is asking for, do you need/want an explicit return in the function?

Consider this example:

const sayHello = name => {
  console.log(`Hello, ${name}!`); //print a string to the console
  return "return executed" //return a string
}

const sayHello2 = name => {
  return `Hello, ${name}!`; //return a string
  name = "virtual.jess"; //this line will never be executed
  console.log(name); //this line will also never be executed
}

console.log(sayHello("Jess")); //call a function and print its return value
console.log(sayHello2("Jess")); //call a function and print its return value

Output:

Hello, Jess!
return executed
Hello, Jess!

1 Like

Thank you Tod! Your explanation helped a lot.
This is my first time trying to learn programming, and sometimes I follow patterns without realizing that I don’t yet understand why I am following them! That leads to things like this :slight_smile: All part of the process, I suppose.
I tried to fix the return on the function, and it still doesn’t work, only this time Codecademy doesn’t tell me anything about why it isn’t working, it just refuses to let me proceed in the quiz.
I added my updated attempt beneath the last one, in case anyone feels like looking at it:

Are you getting an error message? I just ran your code. I get:

ReferenceError: hoursWorked is not defined

The error is here:

  generatePaycheck() {
  let payCheck = this._hoursWorked * this._hourlyWage;
  console.log(payCheck);
  hoursWorked = 0; //the error is complaining about this line. do you have an hoursWorked property? might it be called something else? something quite similar?
  }
1 Like

You could (should probably) use your getters and setter in the method rather than accessing the properties directly:

  generatePaycheck() {
  let payCheck = this.hoursWorked * this.hourlyWage; //using getters to get the values
  console.log(payCheck);
  this.hoursWorked = 0; //using the setter to set the value
  }
1 Like

Ohhh huh, I wonder if there is something going on with my browser. I didn’t get an error at all!
Thanks for letting me know the error, that is way more helpful. I am still figuring out when to use the this._ prepended versions- in a couple of the exercises they use both this._ and the non-prepended version and so it can be a bit confusing sometimes. I will do some extra reading and figure it out.
Your correction worked great, I can finally proceed! Thank you again so much for your help, I really appreciate it.

1 Like

You’re very welcome!

As far as when to use this._someProperty versus this.someProperty, it all kinda revolves around using getters and setters to provide a type of protection to the values of the properties assigned to an object. If your properties are assigned to backing variables (names prepended with the underscore: _propertyOne, _propertyTwo, then you are indicating that you’d like the properties to not be accessed directly. In other words, use getters, setters and methods to update or retrieve property values. By convention, we name getters and setters the same as the property they get or set, but without the underscore. You’ve done this in your code. Getters and setters are special in that we don’t need to use () to execute them. Inside the getter or setter we have to use the name of the property we want to access, so we have to include the underscore. We use this to tell javascript we are referring to this current instance of the object. Hopefully that made at least a little sense.

1 Like

Hello! I had very similar code to Jess’s example above- but instead of this:

set hoursWorked(workedHours) {
this._hoursWorked = workedHours;
}

logHours (num) {
this._hoursWorked += num;
}

I used this:

set hoursWorked(totalHours) {
this._hoursWorked = totalHours;
}

logHours (totalHours) {
this._hoursWorked += totalHours;
}

My question: why does my use of totalHours (as opposed to num) not work?