Home > Net >  Can you spot the 3 Bugs in this JavaScript Code?
Can you spot the 3 Bugs in this JavaScript Code?

Time:07-11

// 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.

CodePudding user response:

Three bugs you have:

  • Firstly, change const with let
  • Secondly, use equal operator == not assign operator
  • Thirdly use template string `` not double quotes

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!

CodePudding user response:

first mistake is line 9 instead of const greeting = this.greeting should be let greeting = this.greeting

second mistake is line 14 instead of if (greeting = undefined) should be if (greeting == undefined)

third mistake is line 18 instead of return "${greeting}, ${name}!"; should be return ${greeting}, ${name}!`;

  • Related