Click here to Skip to main content
15,896,359 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
// 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.
 
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()


What I have tried:

Need help. Javascipt class doesn't work.  When I run it shows me error.
Posted
Updated 27-Oct-21 22:11pm
v2
Comments
Dave Kreskowiak 27-Oct-21 22:19pm    
...and the error would be...?
Patrice T 27-Oct-21 22:20pm    
"When I run it shows me error."
And you plan to show us the error message ?

1 solution

Multiple errors in your code:
JavaScript
if (greeting = undefined)
You are assigning[^] the value undefined to the greeting variable here. Instead, you should be testing for equality[^].

JavaScript
name = "Anonymous";
...
greeting = "Hello";
You have declared both name and greeting as const[^]. That means you cannot change their value. Any attempt to do so will result in an error.

Use let[^] to declare a variable which can be changed.

JavaScript
return "${greeting}, ${name}!";
You are returning the literal string ${greeting}, ${name}!. You should be using a template string[^] instead. That means using back-ticks (`) instead of quotes (" or ') to start and end your string.

JavaScript
g = new Greeter("Hi")
Not technically an error, but you haven't declared the g variable anywhere. Use let g = ... instead.

JavaScript
g.greet()
You're not doing anything with the value returned from this method. You should either store it somewhere for later use, or display it to the user somehow.


In future, make sure you provide a complete and precise description of the error(s) you are trying to solve.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900