0
0
Javascriptprogramming~10 mins

Why classes are introduced in Javascript - Test Your Understanding

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

Complete the code to create a simple object using a class.

Javascript
class Person {
  constructor(name) {
    this.name = [1];
  }
}

const p = new Person('Alice');
console.log(p.name);
Drag options to blanks, or click blank then click option'
APerson
B'name'
Cname
Dthis.name
Attempts:
3 left
💡 Hint
Common Mistakes
Using quotes around name like 'name' assigns a string instead of the parameter value.
Using this.name on the right side causes a reference error because it is not yet defined.
2fill in blank
medium

Complete the code to add a method that returns a greeting.

Javascript
class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return 'Hello, ' + [1] + '!';
  }
}

const p = new Person('Bob');
console.log(p.greet());
Drag options to blanks, or click blank then click option'
Athis.name
Bname
C'name'
DPerson.name
Attempts:
3 left
💡 Hint
Common Mistakes
Using just 'name' refers to a variable not defined in the method scope.
Using quotes 'name' returns the string 'name' instead of the property value.
3fill in blank
hard

Fix the error in the class method to correctly access the property.

Javascript
class Car {
  constructor(model) {
    this.model = model;
  }
  showModel() {
    console.log([1]);
  }
}

const c = new Car('Tesla');
c.showModel();
Drag options to blanks, or click blank then click option'
Amodel
Bthis.model
CCar.model
D'model'
Attempts:
3 left
💡 Hint
Common Mistakes
Using just 'model' causes a reference error because it's not defined in the method.
Using 'Car.model' tries to access a static property which does not exist.
4fill in blank
hard

Fill both blanks to create a class with a method that updates and returns the age.

Javascript
class Animal {
  constructor(age) {
    this.age = age;
  }
  birthday() {
    this.age [1] 1;
    return this.[2];
  }
}

const a = new Animal(3);
console.log(a.birthday());
Drag options to blanks, or click blank then click option'
A+=
B-=
Cage
Dage()
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' subtracts instead of adding.
Returning age() calls a function that does not exist.
5fill in blank
hard

Fill all three blanks to create a class that stores a name, updates it, and returns a greeting.

Javascript
class User {
  constructor([1]) {
    this.name = [2];
  }
  greet() {
    return `Hi, [3]!`;
  }
}

const u = new User('Eve');
console.log(u.greet());
Drag options to blanks, or click blank then click option'
Aname
Cthis.name
D'name'
Attempts:
3 left
💡 Hint
Common Mistakes
Using quotes around 'name' assigns a string instead of the parameter value.
Not using this inside the method causes undefined errors.