GitHub Repository Submission

When using GitHub mode, paste your repository URL below and click Save URL to store it. The saved URL will be automatically included with every message you send until you choose to clear it. Learn more

Your GitHub repository URL is saved. LSBot will automatically fetch your latest code from this repository for each message. To change the URL, clear it first and save a new one.

Exercise 1

Rewrite the following Person class to use private fields for the name and age properties and provide a setter for setting the age property. Ensure that the setter raises a RangeError unless the age is a positive number.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  showAge() {
    console.log(this.age);
  }
}

let person = new Person('John', 30);
person.showAge(); // 30
person.age = 31;
person.showAge(); // 31

try {
  // This line should raise a RangeError,
  // but does not.
  person.age = -5;
  person.showAge(); // -5
} catch (e) {
  //highlight
  // The following line should run, but won't
  console.log('RangeError: Age must be positive');
  //endhighlight
}

Solution

class Person {
  //highlight
  #name;
  #age;
  //endhighlight

  constructor(name, age) {
    //highlight
    this.#name = name;
    this.age = age; // Call the setter to validate data
    //endhighlight
  }

  //highlight
  set age(age) {
    if (typeof(age) === 'number' && age > 0) {
      this.#age = age;
    } else {
      throw new RangeError('Age must be positive');
    }
  }
  //endhighlight

  showAge() {
    //highlight
    console.log(this.#age);
    //endhighlight
  }
}

let person = new Person('John', 30);
person.showAge(); // 30
person.age = 31;
person.showAge(); // 31

try {
  person.age = -5;
  //highlight
  // The following line will not run
  person.showAge();
  //endhighlight
} catch (e) {
  //highlight
  // The following line will run
  console.log('RangeError: Age must be positive');
  //endhighlight
}

Hi! I'm LSBot. I can help you think through the selected exercise by giving you hints and guidance without revealing the solution. Your code from the editor will be automatically detected. Want to know more? Refer to the LSBot User Guide .

Detected solution
Loading...

Submit your solution for LSBot review.

Hi! I'm LSBot. Your code from the editor will be automatically detected. I'll review your solution and provide feedback to help you improve. Ask questions about your solution or request a comprehensive code review. Want to know more? Refer to the LSBot User Guide .

Detected solution
Loading...