Search code examples
javascriptif-statementconditional-statementsgetter-settersetter

If statement works in a function but not in a setter method, and vice versa, also setter not working at all


I'm doing a project on CodeCademy and I need to create a setter method for a number of students. It should check if the value is a number and if it is, return the value, otherwise log an error. I initially came up with this code

set numberOFStudents(val) {
    if(typeof val === 'number') {
      this._numberOfStudents = val;
    } else {
      console.log('Invalid input: numberOfStudents must be set to a Number.') 
    }
  } 

But it didn't work as the value had no effect. It would return both strings and numbers as values. However, when I use this method in a regular function, it works perfectly https://jsfiddle.net/Montinyek/v8zsL5et/12/ The method used in the walkthrough was this:

set numberOfStudents(val) {
    if(val.isNaN()) {
      console.log('Invalid input: numberOfStudents must be set to a Number.')
    } else {
       this._numberOfStudents = val;
    }
  }

Which doesn't work in a regular function as it returns an error https://jsfiddle.net/Montinyek/e6k7qdcs/ But here's what confused me even more, the method used in the walkthrough doesn't seem to have an effect either. I can still set the number of students to a string and it will log it, instead of logging an error. Here's the jsfiddle of the entire code https://jsfiddle.net/Montinyek/1j7wL5gm/


Solution

  • Its because your not using the setter in your constructor. So when you pass in the string it assigns it.

    You need to change

      constructor(name, level, numberOfStudents) {
        this._name = name;
        this._level = level;
        this._numberOfStudents = numberOfStudents;
      }
    

    To

      constructor(name, level, numberOfStudents) {
        this._name = name;
        this._level = level;
        this.numberOfStudents = numberOfStudents;
      }
    

    so it uses the setter and not the member variable. The way in the first directly assigns it to your member instead of using the setter.

    Here is the full code with the change as per your example;

    class School {
      constructor(name, level, numberOfStudents) {
        this._name = name;
        this._level = level;
        this.numberOfStudents = numberOfStudents;
      }
      get name() {
        return this._name;
      }
      get level() {
        return this._level;
      }
      get numberOfStudents() {
        return this._numberOfStudents;
      }
      set numberOfStudents(val) {
        if(typeof val !== 'number') {
          console.log('Invalid input: numberOfStudents must be set to a Number.')
        } else {
           this._numberOfStudents = val;
        }
      }
      quickFacts() {
        console.log(`${this.name} educates ${this.numberOfStudents} students at the ${this.level} school level.`)
      }
      static pickSubstituteTeacher(substituteTeachers) {
        const randInd = Math.floor(Math.random() * substituteTeachers.length)
        return substituteTeachers[randInd];  
      }   
    }
    
    class PrimarySchool extends School {
      constructor(name, numberOfStudents, pickupPolicy) {
        super(name, 'primary', numberOfStudents)
        this._pickupPolicy = pickupPolicy;
      }
      get pickupPolicy() {
        return this._pickupPolicy;
      }
    }
    
    class HighSchool extends School {
      constructor(name, numberOfStudents, sportsTeams) {
        super(name, 'high', numberOfStudents)
        this._sportsTeams = sportsTeams;
      }
      get sportsTeams() {
        return this._sportsTeams;
      }
    }
    
    const lorraineHansburry = new PrimarySchool('Lorraine Hansbury', 'g', 'Students must be picked up by a parent, guardian, or a family member over the age of 13.');
    lorraineHansburry.quickFacts();
    const alSmith = new HighSchool('Al E. Smith', 415, ['Baseball', 'Basketball', 'Volleyball', 'Track and Field'])
    alSmith.quickFacts();
    

    here is the saved jsfiddle showing its working

    https://jsfiddle.net/6qoadu27/6/