Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define an instance method named greet inside the class.
Javascript
class Person { greet() { return [1]; } } const p = new Person(); console.log(p.greet());
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to return a string value.
Using function keyword inside class method.
✗ Incorrect
The instance method greet returns the string 'Hello! I am an instance method.'. The method body must return a string value.
2fill in blank
mediumComplete the code to call the instance method greet on the object p.
Javascript
class Person { greet() { return 'Hi!'; } } const p = new Person(); console.log(p.[1]());
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the class name instead of the method.
Forgetting the parentheses when calling the method.
✗ Incorrect
To call the instance method greet on the object p, use p.greet().
3fill in blank
hardFix the error in the instance method to correctly access the name property.
Javascript
class Person { constructor(name) { this.name = name; } greet() { return 'Hello, ' + [1] + '!'; } } const p = new Person('Alice'); console.log(p.greet());
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the property name without 'this'.
Using class name to access instance properties.
✗ Incorrect
Inside instance methods, use 'this' to access instance properties like name.
4fill in blank
hardFill both blanks to create an instance method that returns the person's full name.
Javascript
class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } fullName() { return [1] + ' ' + [2]; } } const p = new Person('John', 'Doe'); console.log(p.fullName());
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using property names without 'this'.
Forgetting to add space between names.
✗ Incorrect
Use 'this.firstName' and 'this.lastName' to access the instance properties inside the method.
5fill in blank
hardFill all three blanks to create an instance method that updates the person's age and returns a message.
Javascript
class Person { constructor(name, age) { this.name = name; this.age = age; } haveBirthday() { this.age = this.age [1] 1; return `$[2] is now $[3] years old.`; } } const p = new Person('Emma', 29); console.log(p.haveBirthday());
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' to increment age.
Not using 'this' to access properties.
Incorrect template literal syntax.
✗ Incorrect
The method increments age by 1 using '+', then returns a message using this.name and this.age.