javascripthtmldebuggingsyntaxconstructor

Can you spot the 3 Bugs in this JavaScript Code?


// This class takes a name string and greeting string in
// the constructor. Here are some examples of how this should work:
//
// g = new Greeter()
// g.greet() # => "Hello, Anonymous!"
//
// g = new Greeter("What's up", "Dog")
// g.greet() # => "What's up, Dog!"
//
// g = new Greeter("Hola")
// g.greet() # => "Hola, Anonymous!"
 
// Unfortunately, this code isn't quite working.
// Can you spot at least 2 bugs?
 
class Greeter {
  constructor(name, greeting) {
    this.name = name;
    this.greeting = greeting;
  }
    
  greet() {
    const name = this.name;
    const greeting = this.greeting;
    
    if (!name) {
      name = "Anonymous";
    }
    if (greeting = undefined) {
      greeting = "Hello";
    }
    
    return "${greeting}, ${name}!";
  }
}
 
g = new Greeter("Hi")
g.greet()

Having trouble with my online assignment. I'm not too familiar with using constructors for Classes so I cant find what's wrong with the syntax.

  1. So far I've only identified using "const" as 1 bug, since that triggered the "Assignment to Constant Variable" error.

Solution

  • Three bugs you have:

    fixed:

    class Greeter {
        constructor(name, greeting) {
        this.name = name;
        this.greeting = greeting;
        }
    
        greet() {
        //1
        let name = this.name;
        let greeting = this.greeting;
    
        if (!name) {
            name = "Anonymous";
        }
        if (greeting == undefined) {
            //2
            greeting = "Hello";
        }
    
        return `${greeting}, ${name}!`; //3
        }
    }
    
    g = new Greeter("Hi");
    g.greet(); //Hello, Hi!