0
0
Javascriptprogramming~10 mins

Instance methods in Javascript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A'Hello! I am an instance method.'
BHello
Cgreet
Dfunction greet()
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to return a string value.
Using function keyword inside class method.
2fill in blank
medium

Complete 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'
Athis
BPerson
Cnew
Dgreet
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the class name instead of the method.
Forgetting the parentheses when calling the method.
3fill in blank
hard

Fix 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'
Aself.name
Bname
Cthis.name
DPerson.name
Attempts:
3 left
💡 Hint
Common Mistakes
Using the property name without 'this'.
Using class name to access instance properties.
4fill in blank
hard

Fill 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'
Athis.firstName
BfirstName
Cthis.lastName
DlastName
Attempts:
3 left
💡 Hint
Common Mistakes
Using property names without 'this'.
Forgetting to add space between names.
5fill in blank
hard

Fill 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'
A+
Bthis.name
Cthis.age
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' to increment age.
Not using 'this' to access properties.
Incorrect template literal syntax.