JavaScript Essentials 2 –  JSE2: Module 2: Classes and Class-Based Approach Module 2 Test Exam Answers Full 100%

Mastering JavaScript is a journey that becomes progressively more rewarding as you delve into its advanced concepts. JavaScript Essentials 2 (JSE2) builds upon foundational knowledge, guiding you through more sophisticated programming techniques. In Module 2, the focus shifts to Classes and the Class-Based Approach, a critical aspect of modern JavaScript development. This post provides the complete set of answers for the Module 2 Test Exam, ensuring you achieve a full 100%. By thoroughly understanding these concepts and their applications, you’ll enhance your coding skills and confidence. Whether you’re preparing for the test or reinforcing your learning, this guide offers the insights needed for success. Let’s dive into the key answers and solidify your grasp of JavaScript Classes!

  1. A class may have a constructor, i.e. a method:

    • of any name that will be defined first in the class.
    • named this.
    • of any name preceded by the word constructor.
    • named constructor.
      Explanation & Hint:

      In JavaScript classes, the constructor is a special method that is automatically called when an instance of the class is created. It must have the name “constructor” (case-sensitive) and is used to initialize object properties and perform any setup needed for instances of the class.

  2. You have defined a class Point whose constructor takes two arguments: x and y. Which of the following is the correct way to create a point object of this class?

    • let point = Point(100, 200);
    • let point = create Point(100, 200);
    • Point(let point, 100, 200);
    • let point = new Point(100, 200);
      Explanation & Hint:

      The correct way to create a point object of the class Point with a constructor that takes two arguments, x and y, is:

      let point = new Point(100, 200);

      This correctly creates a new instance of the Point class with the x and y values set to 100 and 200, respectively.

  3. There is one line missing in the code below:

    class User {
        // Insert line of code here.
        showName() {
            console.log(this.name);
        }
    }
    let user = new User('Alice');
    user.showName();

    Select the correct missing line so that the executed code results in the following console output: Alice

    • constructor function(n) { name = n;}
    • constructor(n) { this.name = n;}
    • constructor(n) { name = n;}
    • User(n) { this.name = n;}
      Explanation & Hint:

      The correct missing line of code to achieve the desired console output “Alice” after running the whole code is:

      constructor(n) { this.name = n;}

      It defines the constructor for the User class, which takes a parameter n and assigns it to the name property of instances.

  4. Analyze the following code:

    let Point class {};

    It is:

    • correct, because it is the creation of an object based on an empty class, and saves it to the Point variable.
    • incorrect, because it should be: class Point {};
    • incorrect, because a class definition (the content of the brackets) can’t be empty.
    • correct, because it is a declaration of an anonymous class, and saves it to the variable Point (a class as a first-class citizen).
      Explanation & Hint:

      The correct answer is:

      correct, because it is a declaration of an anonymous class, and saves it to the variable Point (a class as a first-class citizen).

      The code let Point = class {}; is indeed a correct declaration of an anonymous class in JavaScript. It defines an empty class and assigns it to the variable Point. In JavaScript, classes are first-class citizens, which means you can assign them to variables just like any other value.

  5. There is one line missing in the code below:

    class A {
        // Insert line of code here.
    }

    Select the correct missing line in order to declare a property named test and initialize it with the value 10:

    • test = 10;
    • test: 10;
    • test: 10
    • this.test = 10;
      Explanation & Hint:

      The correct missing line of code to declare a property named test and initialize it with the value 10 in the A class is:

      test = 10;

      It uses the modern class field syntax to declare and initialize the test property with the value 10 directly within the class definition.

  6. Analyze the following code:

    class User {
        constructor (x, y) {
            this.x = x;
            this.y = y;
        }
    
        setColor(color) {
            this.color = color;
        }
    }
    let point = new Point(100, 200);
    point.setColor('red');

    The point object:

    • has three properties: x, y and color.
    • will not be created – setColor references a color property that was not defined in the constructor.
    • will not be created – the constructor and the setColor method refer to properties that have not been defined in the class body.
    • has two properties: x and y (only these are defined in the constructor)
      Explanation & Hint:

      The correct answer is:

      has three properties: x, y, and color

      The Point class has a constructor that initializes x and y properties, and a setColor method that sets the color property. When you create a new instance of the Point class using let point = new Point(100, 200);, you’re calling the constructor with x and y values, which initializes the x and y properties of the point object. Then, you call the setColor(‘red’) method on the point object, which sets the color property to ‘red’.

  7. Analyze the following code:

    class Point {
        name = 'Point';
        constructor (x, y) {
            this.x = x;
            this.y = y;
        }
    
        setColor(color) {
            this.color = color;
        }
    }
    let point = new Point(100, 200);
    point.setColor('red');

    Which of the following properties will the point object have?

    • x y
    • name
    • name x y
    • name x y color
      Explanation & Hint:

      The correct option is:

      name x y color

      The name property is defined with a default value of ‘Point’ at the class level using the class field syntax. This means that all instances of the Point class will have a name property with the value ‘Point’. The x and y properties are initialized in the constructor, so they will exist on the point object after you create it with new Point(100, 200);. The color property is set using the setColor method, so it will also exist on the point object after you call point.setColor(‘red’);.

  8. There is one line missing in the code below:

    class User {
        // Insert line of code here.
        get name() {return this.#name;}
    }
    let point = new User();
    point.x = 10;

    Select the correct missing line in order to insert a private property declaration in the code:

    • name = 'Bob';
    • private name = 'Bob'
    • #name = 'Bob';
    • this.#name = 'Bob';
      Explanation & Hint:

      The correct missing line of code to insert a private property declaration in the code is:

      #name = ‘Bob’;

      It uses the # symbol to declare a private class field named #name and initializes it with the value ‘Bob’.

  9. Analyze the following code:

    class Point {
        #x = 0;
        #y = 0;
        color = 'red';
    }
    let point = new Point();
    console.log(Object.keys(point));

    What will appear in the console as a result of code execution?

    • ['color']
    • []
    • ['x', 'y', 'color']
    • ['#x', '#y', 'color']
      Explanation & Hint:

      The code will result in the following appearing in the console:

      [‘color’]

      In the Point class, there are three properties defined:

      • #x (a private field)
      • #y (a private field)
      • color (a public property)

      When you create a new instance of the Point class with let point = new Point();, it initializes these properties with their default values. However, when you use Object.keys(point) to get an array of the object’s own property names, it only includes the public property color. Private fields (such as #x and #y) are not included in the list when you use Object.keys(), which is why you see [‘color’] in the console.

  10. Analyze the following code:

    class User {};
    let user = new User();
    console.log(`${user instanceof User} ${typeof(user)}`);

    What will appear in the console as a result of code execution?

    • true object
    • User User
    • true User
    • User object
      Explanation & Hint:

      The code will result in the following appearing in the console:

      true object

      user instanceof User checks if the user object is an instance of the User class. In this case, it evaluates to true because user was created using new User();, which makes it an instance of the User class. typeof(user) returns the type of the user object, which is ‘object’. In JavaScript, instances of classes are of type ‘object’. So, the code console.log(${user instanceof User} ${typeof(user)}); logs true (indicating that user is an instance of User) and ‘object’ (indicating that the type of user is an object).

  11. Analyze the following code:

    class User {
        constructor(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }
        get fullName()  {return `${this.firstName} ${this.lastName}`}
    }
    let user = new User('Bob Marley');

    Select the correct command in order for the console to show the following string after running the whole code: Bob Marley

    • console.log(user.getfullName); 
    • console.log(user.fullName());
    • console.log(user.fullName);
    • console.log(user['get fullName']);
      Explanation & Hint:

      The correct command to use in order for the console to show the following string “Bob Marley” after running the whole code is:

      console.log(user.fullName);

      It accesses the fullName getter method of the user object, which returns the full name as “Bob Marley”.

  12. There is one line missing in the code below:

    class User {
        _name = 'Alice';
        // Insert line of code here.
    }
    let user = new User();
    user.name = 'Bob';
    console.log(user._name);

    Select the correct missing line in order for the console to show the following after running the whole code: Bob

    • set _name(name) { this._name = name;} 
    • _name set(name) { this._name = name;}
    • set (name) { this._name = name;}
    • set name(val) { this._name = val;}
      Explanation & Hint:

      The correct missing line of code to set the name property in the User class and allow the console to show “Bob” after running the whole code is:

      set name(val) { this._name = val;}

      It defines a setter for the name property, which sets the private _name property to the provided val.

  13. There is one line missing in the code below:

    class A {
        test1() { return 'A';}
    }
    // Insert line of code here.
        test2() { return 'B';}
    }
    let b = new B();
    console.log(`${b.test1()} ${b.test2()}`);

    Select the correct missing line so that the executed code results in the following console output: A B

    • class A extends B {
    • A inherits B {
    • B inherits A {
    • class B extends A {
      Explanation & Hint:

      The correct missing line of code to make the code result in the desired console output “A B” is:

      class B extends A {

      It defines the class B as extending the class A, which allows B to inherit the test1 method from A.

  14. Analyze the following code:

    class User {};
    class EUser extends User {};
    class EEUser extends EUser {};
    let eeuser = new EEUser();
    console.log(`${eeuser instanceof User} ${eeuser instanceof EUser} ${eeuser instanceof EEUser}`);

    What will appear in the console as a result of code execution?

    • false false true
    • true false false
    • true true true
    • false false false
      Explanation & Hint:

      The code will result in the following appearing in the console:

      true true true

      eeuser is an instance of the EEUser class. The EEUser class extends the EUser class, and the EUser class extends the User class. JavaScript’s instanceof operator checks if an object is an instance of a particular class or its descendants in the prototype chain. Since EEUser extends EUser, and EUser extends User, eeuser is considered an instance of all three classes: User, EUser, and EEUser. So, all three conditions eeuser instanceof User, eeuser instanceof EUser, and eeuser instanceof EEUser evaluate to true, resulting in “true true true” being logged to the console.

  15. Analyze the following code:

    class A {
        getName() {
            return 'A';
        }
    }
    
    class B extends A {
        getName() {
            return 'B';
        }
        test(x) {
            return x ? this.getName() : super.getName();
        }
    }
    
    let b = new B();
    console.log(`${b.test(true)} ${b.test(false)}`);

    What will appear in the console as a result of code execution?

    • A A
    • B B
    • B A
    • A B
      Explanation & Hint:

      The code will result in the following appearing in the console:

      B A

      The B class extends the A class and overrides the getName method. In the B class, the getName method returns ‘B’. The test method in the B class takes an argument x. If x is truthy (in this case, true), it calls this.getName(), which calls the overridden getName method in the B class, returning ‘B’. If x is falsy (in this case, false), it calls super.getName(), which refers to the getName method of the superclass A. So, it returns ‘A’. Therefore, when you call b.test(true), it returns ‘B’, and when you call b.test(false), it returns ‘A’. So, the result is “B A”.

  16. There is one line missing in the code below:

    class A {
        constructor(val) {
            console.log(`A: ${val}`);
        }
    }
    
    class B extends A {
        constructor(val) {
            // Insert line of code here.
            console.log(`B: ${val}`);
        }
    }
    
    let b = new B(10);

    Select the correct missing line so that the executed code results in the following console output:
    A: 10
    B: 10

    • A(val);
    • this = new A(val);
    • super(val);
    • An empty line
      Explanation & Hint:

      The correct missing line of code to make the executed code result in the desired console output “A: 10 B: 10” is:

      super(val);

      It calls the constructor of the superclass A with the val argument, ensuring that the A class constructor is executed before the B class constructor.

  17. A static method defined in a class:

    • is visible only in the object created from the class, but can only be called by other methods of the object.
    • is bound to the class only and will not be available in the object created from it.
    • is visible both in the class and in the object created from it (it can be called in both).
    • is visible only in the object created from the class and can be called arbitrarily in that object.
      Explanation & Hint:

      The correct answer is:

      is bound to the class only and will not be available in the object created from it.

      A static method is associated with the class itself, not with instances (objects) created from the class. It is defined on the class and can be called on the class itself, rather than on instances of the class. Static methods are not available on instances of the class. They are not bound to individual objects and cannot access or modify instance-specific data or properties. Static methods are often used for utility functions or operations that are relevant to the class as a whole, rather than to specific instances.

  18. You have declared the class Test and create a test object from it:

    class Test {
        static info() { return'Test';}
    }
    
    test = new Test();

    Select the correct call so that the executed code results in the following console output: Test 

    • Test.info()
    • test['static info']()
    • test.info()
    • Test.info
      Explanation & Hint:

      The correct call to make the executed code result in the desired console output “Test” is:

      Test.info()

      This is the correct choice. It calls the static method info() on the Test class, which returns ‘Test’.

  19. Analyze the following code:

    function A() {};
    class B extends A {};
    let b = new B();
    console.log(`${b instanceof A} ${b instanceof B}`);

    As a result of its execution:

    • false false will be displayed, because B inheriting from A will also be a function.
    • true true will be displayed, because A will be treated as a constructor during inheritance.
    • an error will appear because you are trying to inherit in class B from function A and not from another class.
    • false true will be displayed, because A is not a class.
      Explanation & Hint:

      The correct result of executing the provided code is:

      true true will be displayed, because A will be treated as a constructor during inheritance.

      The A function in the code acts as a constructor function, and the B class extends A. This inheritance means that B inherits the prototype chain of A. When you create an instance b of class B with new B();, it is also an instance of the A constructor function because of the inheritance relationship. Therefore, b instanceof A evaluates to true because b is an instance of both A and B. Similarly, b instanceof B evaluates to true because b is also an instance of class B.

Leave a Reply