Back to Week-5

Week 5 Quiz

Explain what "npm" stands for.

Node Package Manager

Explain the purpose of the package.json file and node_modules directory.

Given multiple choices, identify the difference between npm's package.json and package-lock.json files.

How do you check what version of npm is current installed?

npm -v or npm --version

How do you update npm to the latest version?

npm install -g npm

Name the steps to setup a new npm project

Give a package version number, how do you indicate any version above the major version 1

> 1.0.0 indicates "any version above the major version 1" //could be 2.0.0, 4.0.0, 5.1.12

Given a package version number, how do you indicate any version in the 1.x.x range?

^1.0.0 indicates "any version in the 1.x.x range."

Given a package version number, how do you indicate any version in the patch range (1.0.x)

~1.0.0 indicates "any patch version in the 1.0.x range"

Given a package version number, how do you indicate an exact version?

1.0.0 indicates "exactly version 1.0.0"

Explain the difference between a dependency and a development dependency

What are the steps to clone an existing gitHub repo?

How do you uninstall a dependency you no longer need?

npm uninstall <moduleName>>

What are the steps to locating a new module that is reputable?

How do you fix a package with vulnerabilities due to outdated versions?

Use npm audit --fix. If the fix requires you to step up to the next major build, you may need to use npm audit --fix --force but be prepared to have to fix other parts of your program.

How would you write and run an npm script to count the number of lines in files in your directory that end in .js?

  1. In package.json, under the scripts: key, create a new subkey, naming it.
  2. The value of this new key will be your script: "wc -l *.js"
  3. Execute the script from the npm cli using npm run <newKeyName>

What is the definition of a JavaScript Prototype

In JavaScript, a prototype is an object that is delegated to when a reference to an object property or method can't be resolved.

For example, if a property or method isn't available on an object, JavaScript will delegate to the object's prototype to see if that object has the requested property or method. If the property or method is found on the prototype, then the action is carried out on the prototype object. The delegation to the prototype happens automatically, so from the caller's perspective it looks as if the original object had the request property or method.

In JavaScript, you can make an object the prototype of another object. When an object is a prototype of another object, it's properties and methods are made available to the other object.

How do you define an ES5 class?

In ES5 creating a class uses a constructor function

The constructor function is ONLY a constructor. Use Object.setPrototype to create a method for that class.

function Book(title, series, author) {
	if (!(this instanceof Book)) {
		//Throws a custom error when `Book` is called without the `new` keyword
		throw new Error('Book needs to be called with the `new` keyword');
	}
	this.title = title;
	this.series = series;
	this.author = author;
}

How do you define an ES5 class method:

    Book.prototype.getInformation = function() {
        return `${this.title} by ${this.author}`;
    };

In ES5, what happens if you create an instance of a class without using "new"

Referencing the "new instance" returns undefined.

May be better to add a if (!(this instanceof Book)) { throw new Error('new error' } in the constructor, or if you're uncertain of the object use instanceOf() to make sure before calling the class methods.

How do you define an ES6 class

    class MMS {
         constructor(recipient, sender, text, mimeType) {
             this.recipient = recipient;
             this.sender = sender;
             this.text = text;
             this.mimeType = mimeType;
         }

    }

What is a static method, and how do you call it?

A static method is a method that is performed on the class, not the instance of the class. To call a static method you need the class name (not the object) to call it. For instance:

    class MMS {
        constructor (recipient, sender, text, mimeType) {
            this.recipient = recipient;
            this.sender = sender;
            this.text = text;
            this.mimeType = mimeType;
        }
        static getMessagesByMIMEType(messages, mimeType) {
            return messages.filter(m => m.mimeType === mimeType);
        }
    }

    const instance1 = new MMS('555-111-1111', '555-222-2222', 'This is a test message.', 'image/gif');
    const instance2 = new MMS('555-111-1111', '555-222-2222', 'This is a test message.', 'image/gif');
    const instance3 = new MMS('555-111-1111', '555-222-2222', 'This is a test message.', 'image/jpeg');
    const instance4 = new MMS('555-111-1111', '555-222-2222', 'This is a test message.', 'image/gif');

    const messages = [instance1, instance2, instance3, instance4];

    const filteredMessages = MMS.getMessagesByMIMEType(messages, 'image/gif');

    console.log(filteredMessages);

Your parent class has static vars declared in it. You want to overwrite the static var by assigning a new value. How do you do it?

In your child class, you define a static var with the same name as in the parent class, then assign it the value you want.

How do you export Classes out of a module in commonJS?

  1. module.exports = { Cat, Dog }
  2. module.exports = { specialCat: Cat, specialDog: Dog }

Although you can also export using the exports.specialCat = Cat; or exports.Animal; it's best not to use this syntax as it's easily confused with another Exports

For the methods shown in the previous question for commonJS, how do you import the Cat and Dog classes?

  1. module.exports = { Cat, Dog }
    const { Cat, Dog } = require('./animals');
  2. module.exports = { specialCat: Cat, specialDog: Dog }
    const { specialCat, specialDog } = require('./animals');
  3. exports.specialCat = Cat; exports.specialDog = Dog;
    const { specialCat, specialDog } = require('./animals');
  4. exports.Animals
    const { Animals } = require('Animals')
    but then you need to reference the other classes as Animal.Cat and Animal.Dog;

How do you declare a private variable in an ES6 class?

#color = "red"; above your constructor. Then when referencing it in your class methods, use this.#color

What are the 4 Pillars of Object-Oriented Programming (OOP)

  1. Encapsulation : Combining the behavior (the methods) and the data it works on (ie instance variables).
  2. Inheritance: Javascript, in particular, supports implementation inheritance through a mechanism known as prototypal inheritance.
    1. Implementation inheritance: The data and methods defined on a parent class are available on objects created from classes that interit from those parent classes.
    2. Prototypal inheritance: JavaScript uses prototype objects to make its implementation inheritance actually work
  3. Polymorphism: You can treat a variable as if it were one of its parent types, meaning that you can use the methods of a parent class on an object of a child class.
  4. Abstraction: Until ES6, JavaScript did not support abstraction. Now, through the use of #<var> you can abstract variables by hiding them from the outside. These vars are only accessible from within the function. Please note: If asked on a quiz - likely abstraction will NOT be one of the pillars of OOP.

Define Encapsulation

The mechanism that puts behavior and data together behind methods that hide the specific implementation of a class.

Define Inheritance

The mechanism that passes traits of a parent class to its descendants.

Define implementation inheritance

The data and methods defined on a parent class are available on objects created from classes that inherit from those parent classes

Define prototypal inheritance

A method of realizing implementation inheritance through process of finding missing properties on an object by delegating the resolution to a prototype object.

What is the extends keyword?

The keyword in JavaScript that allows one class to inherit from another.

What is the constructor method?

The special method of a class that is called to initialize an object when code uses the new keyword to instantiate an object from that class.

What is the Single-Responsibility-Principle?

Any one of the following:

What is the Liskov Substitution Principle?

You can substitute child class objects for parent class objects and not cause errors.

What is the Open-Close Principle?

A class is open for extension and closed for modification.

What is the Interface Segregation Principle?

Method names should be grouped together into granular collections called "interfaces"

What is The Dependency Inversion Principle?

Functionality that your class depends on should be provided as parameters to methods rather than using new in the class to create a new instance of a dependency.

What is the Law of Demeter?

Don't use more than one dot (not counting the one after "this").

What are 5 kinds of objects a method of an object can invoke (or use the properties of)?

>

How do CommonJS Modules allow other modules to access exported symbols?

Through the use of the module.exports property.

How do ES6 Modules export functionality so other modules can use them?

Through the use of export

How can a CommonJS Module import functionality from another module?

Through the use of the require function.

How can an ES6 module import functionality from another module?

Through the use of the import-from syntax that looks like this: import SymbolName from './relative-path.js';

What is the mechanism that passes traits of a parent class to its descendants.

Inheritance

What is the extends keyword used for?

The keyword in JavaScript that allows one class to inherit from another.

What is the constructor method?

The special method of a class that is called to initialize an object when code uses the new keyword to instantiate an object from that class.

What are the data and methods defined on a parent class are available on objects created from classes that inherit from those parent classes called?

Implementation inheritance

What is defined as : A method of realizing implementation inheritance through process of finding missing properties on an object by delegating the resolution to a prototype object.

Prototypal inheritance

What is tunctionality that your class depends on should be provided as parameters to methods rather than using new in the class to create a new instance of a dependency?

The Dependency Inversion Principle

What is a short definition of The Law of Demeter?

Don't use more than one dot (not counting the one after "this")

What is the following called?

The Law of Demeter

What is the mechanism called that puts behavior and data together behind methods that hide the specific implementation of a class?

Encapsulation

The keyword in JavaScript that allows one class to inherit from another.

The extends keyword

What is the special method of a class that is called to initialize an object when code uses the new keyword to instantiate an object from that class?

The constructor method.

Any one of the following:

  1. A class should do one thing and do it well.
  2. A class should have only one reason to change
  3. Gather together the things that change for the same reasons. Separate those things that change for different reasons.

The Single-Responsibility Principle

What is it called when you can substitute child class objects for parent class objects and not cause errors.

The Liskov Substitution Principle

What is it called when a class is open for extension and closed for modification?

The Open-Close Principle

Method names should be grouped together into granular collections called "interfaces"

The Interface Segregation Principle

Don't use more than one dot (not counting the one after "this").

The Law Of Demeter

Through the use of the module.exports property.

How do CommonJS Modules allow other modules to access exported symbols?

Through the use of the export keyword.

How do ES6 Modules export functionality so other modules can use them?

Through the use of the require function.

How can a CommonJS Module import functionality from another module?

Through the use of the import-from syntax that looks like this: import SymbolName from './relative-path.js';

How can an ES6 module import functionality from another module?

Which of following is the definition of the "polymorphism" object-oriented principle?

  1. You cannot call any methods on the object.
  2. You can treat an object as an instance of its own class and only its direct parent class (prototype).
  3. You can treat an object as an instance of its own class and none of its parent classes (prototypes).
  4. You can treat an object as an instance of its own class and all of its parent classes (prototypes).

#4. You can treat an object as an instance of its own class and all of its parent classes (prototypes).

EXPLANATION: Polymorphism allows you to treat the object as its own class or any of its parent classes (prototypes). This allows code that uses the object to take advantage of the behavior that it inherits from its parent classes (prototypes).

With respect to object-oriented programming, what is a "constructor"?

  1. A constructor is a method used to allocate memory on the computer and is called when the program starts.
  2. A constructor is a method used to initialize the state of an object at the time of object creation.
  3. A constructor is a class that creates other classes.
  4. A constructor

#2: A constructor is a method used to initialize the state of an object at the time of object creation.

EXPLANATION: The special method known as a "constructor" provides the object-oriented system a way to initialize the state of an object and ensure all of its information dependencies are met.

Choose two or more of the following that describe what a "class" is in JavaScript.

  1. A class is the collection of behavior and data that an object should have.
  2. A class is a template by which objects are created using the new keyword.
  3. A class is the mechanism by which the primitive values of numbers, Booleans, null, and undefined are represented in JavaScript.
  4. A class is a representation of the implementation of an object that you want to create.

#1, #2, #4

EXPLANATION: The representation of the object is like a blueprint for the behavior (methods) and data (fields) that will be associated with and available on the object constructed from the class.

Which one of the following types of inheritance does JavaScript support?

  1. Implementation inheritance where, given an object, code can invoke methods on the object defined on "parent" classes (prototypes).
  2. Interface inheritance where a class must implement any undefined methods of its parent class (prototype).
  3. Identity inheritance where each object gets an identity which is used to identify that object from its parent class (prototype).
  4. Iterative inheritance where each iteration of the parent class (prototype) is used to increment the version of the object created from it.

#1 EXPLANATION: JavaScript has implementation inheritance which means that an object will inherit the implementation of the methods and data from its parent classes (prototypes) unless otherwise overridden.

Which of following is the definition of the "inheritance" object-oriented principle?

  1. Inheritance is the mechanism by which a programmer can copy and paste code from one file to another.
  2. Inheritance is the mechanism by which an object acquires the behavior (and data) from the definition of its parent class (prototype).
  3. Inheritance is the mechanism by which an object passes information from its constructor to an instance method defined for that object.
  4. Inheritance is the ability to provide multiple methods with the same name.

#2: EXPLANATION: Inheritance is a way to write code in methods and share those between other classes to reduce the maintenance cost and promote easy-to-understand code.

In JavaScript, for a class declared using the ES6 syntax and named Animalj, what is the name of its constructor method?

  1. ctor
  2. animal
  3. constructor
  4. Animal

#3 EXPLANATION: In JavaScript, the special method named constructor is the method run at the time the object is created.

Question

#3

Which of following is the definition of the "encapsulation" object-oriented principle?

  1. Providing more than one way to create an object from a class.
  2. Putting your data into a "module" (or "capsule") so that it is easy to import and export.
  3. A method by which a programmer can increase the coupling between components.
  4. Providing a simple way to interact with a potentially complex implementation of a concept.

#4 EXPLANATION: The object-oriented principle of "encapsulation" is the method by which a programmer can provide a simple way to interact with the potentially complex implementation of a concept. Code that uses the simple way needs not know the data types that make up the state of the object nor the implementation of each of the behavioral methods on the class.

Which of the following keywords does JavaScript support to call methods on a parent class (prototype) when defined with ES6 syntax?

  1. prototype
  2. parent
  3. base
  4. super

#4 EXPLANATION: The ES6 syntax for declaring classes provides the super keyword with which to access methods on a parent class (prototype)

The "L" in the SOLID Principles stands for the Liskov Substitution Principle. If a class abides by it, what does that mean for the class?

  1. Any method that the object overrides from its parent must include a call to super in it.
  2. Any method that the object overrides from its parent class must not drastically differ from that of the method on the parent class.
  3. The class should substitute its own instance fields for all of those in its parent class./li>
  4. Any method parameter can be substituted with another object of a different type and still work.

#2 EXPLANATION: The Liskov Substitution Principle has a very mathematically-based definition, but can be interpreted to mean that any method that a class overrides from its parent class must have similar behavior with respect to the original method.

What does the "D" in the SOLID Principles stand for?

  1. The Disparate Interface Principle
  2. The Data Over Behavior Principle
  3. The Dependency Inversion Principle
  4. The Dependant Property Principle

#3 EXPLANATION: The "D" in SOLID is the Dependency Inversion Principle. This is the principle that says a high-level module should not depend on low-level modules but on abstractions, instead. Detailed implementations should rely only on abstractions. This is primarily useful to follow in languages like C++ and Java.

What does the "O" in the SOLID Principles stand for?

  1. The Overloading Principle
  2. The Overriding Principle
  3. The Open-Close Principle
  4. The Open-Class Principle

#3 EXPLANATION: The "O" in SOLID is the Open-Close Principle. This is the principle that says a class should be open for extension but closed for modification. This is primarily useful to follow in languages like C++ and Java.

The "S" in the SOLID Principles stands for the Single-Reponsibility Principle. If a class abides by it, what does that mean for the class?

  1. A class has a single set of curly braces.
  2. A class has a single reason to change.
  3. A class has a single instance in the running program.
  4. A class has a single constructor to initialize itself.

#2 EXPLANATION: The Single-Responsibility Principle means that a class should have only one reason to change. This means that the methods and data in a class reflect one idea and one idea only. This prevents classes from doing too much which drastically lowers the maintainability of the code base.

What does the "I" in the SOLID Principles stand for?

  1. The Implementation Override Principle
  2. The Interface Segregation Principle
  3. The Inheritance Principle
  4. The Internal Methods Principle

#2 EXPLANATION: The "I" in SOLID is the Interface Segregation Principle. This is the principle that says a class should implement many cohesive interfaces rather than one combined interface. This is primarily useful to follow in languages like C++ and Java.

Explain how the Law of Demeter prevents tight coupling between types.

The Law of Demeter:
The Law of Demeter requires that an object have the least knowledge about other types. Therefore, it can only call methods on the following kinds of objects:

  1. Its own methods (through the this keyword)
  2. Methods of objects passed through a parameter
  3. An objects created in the method
  4. Objects stored in its own data fields
  5. Any values stored in global variables


This usually manifests itself as meaning, you can only use one dot on objects and not chain them together.

Explain what "npm" stands for

NPM stands for the Node Package Manager, and it is used to refer to a number of different things:

Explain the purpose of the package.json file and node_modules directory.

Given multiple choices, identify the difference between npm's package.json and package-lock.json files.

  1. package.json stores vague package versions - but not specific versions, while package-lock.json contains the exact package versions that are installed.
  2. package.json can be modified by hand, but package - lock.json typically is generated.
  3. package.json can be created by npm init
  4. package.json stores a range of acceptable dependency versions, package-lock.json stores an exact version

How do you check which version is running in npm?

npm --version [checks what version is currently installed]. Use npm update to update itself to the latest version. Use npm use <version> to use a different version you have installed

What are the steps to start a new project, add a package as a dependency, then access the package in a JavaScript file?

  1. Use npm init --yes [To create a new package]
  2. Use npm install lodash [To install the lodash package.]
  3. Use const lodash = require('lodash'); to include this in your JavaScript file
  4. Use console.log(loadash.VERSION) to print out the version of loadash
  5. Use node index.js to run your index.js file

Describe what semver characters mean next to version numbers in the package.json file

  1. * means literally the newest version
  2. 14.16.1 means exactly the version 14.16.1
  3. ~14.16.1 will match any package with a matching minor version and a larger patch version
  4. ^14.16.1 will match any package with a larger minor and patch version.

In the version 14.16.1, which is the minor version number?

16

In the version 14.16.1, which is the patch version number?

1

Explain the difference between a dependency and a development dependency

A dependency is required by your app at runtime - it may or may not be needed when doing testing, or during development.

A development dependency is only required by your app at development time. Common development dependencies are testing libries like chai.

Given an existing GitHub repository, clone the repo and use npm to install it's dependencies

  1. git clone <some_repo>
  2. npm install

Use npm to remove a dependency

npm uninstall <dependency package name>

Use npm update to update an out-of-date dependensy like lodash

npm lodash@latest

Given a problem description, what steps would you use to find a reputable package that provides the functionality to solve that problem?

Go to npmjs.com; Search for packages. Consider the following:

  1. Does the API handle the task you need to accomplish?
  2. Does the project have a significant number of downloads?
  3. In version control, are there recent commits, issues, pull requests?
  4. When was the last version released?

You've installed an npm package, but you see there are outdated dependency versions which cause vulnerabilities. How would you fix this?

use npm audit --fix. If you have to update to a different build, beware that this could impact other portions of your code. However, if you're certain this is what needs to be done, use npm audit --force and be ready for warning messages.

How would you write, and run an npm script?

  1. In package.json, under the scripts: key, create a new key with your script name
  2. The value of this new key will be your script.
  3. To run the script, use npm run <scriptKeyName>

Define a constructor function using ES5 syntax

function Apartment(address, bedrooms, baths) {
    this.address = address;
    this.bedroom = bedrooms;
    this.baths = baths;
}
                        

Define a method on the class you just created using ES5 syntax:

    Apartment.prototype.printListing = function() {
        console.log(`This fabulous ${this.bedrooms} bedroom apartment,
             located at ${this.address} has ${this.baths} luxuriant
             bathrooms for all your evacuating needs.`);
    }
                        


NOTE: do NOT use arrow functions because we want this to be bound when the function is called, not where the function is defined.

How do you run the method on your ES5 class?

    const apt = new Apartment('1987 Squirtle Ave', 2, 2);

    apt.printListing();
                        

Declare a class using ES6 syntax


class Apartment {
    constructor(address, bedrooms, baths) {
        this.address = address;
        this.bedrooms = bedrooms;
        this.baths = baths;
    }
}
                        

Define an instance method on an ES6 class


class Apartment {
    constructor(address, bedrooms, baths) {
        this.address = address;
        this.bedrooms = bedrooms;
        this.baths = baths;
    }

    printListing() {
        console.log(`This fabulous ${this.bedrooms} bedroom apartment,
        located at ${this.address} has ${this.baths} luxuriant
        bathrooms for all your evacuating needs.`);
    }
}
                                                

Define a static method on an ES6 class:

class Apartment {
    //Somewhere in the class

    static compareTwo(apartment1, apartment2) {
        if (apartment1.bedrooms - apartment2.bedrooms > 0{
            return apartment1;
        } else if (apartment1.bedrooms - apartment2.bedrooms < 0) {
            return apartment2;
        } else {
            return apartment1;
        }
    }
}

Create two new instances of Apartment

apartment1 = new Apartment('1987 Squirtle Ave', 2, 2);
apartment2 = new Apartment('2000 Wilougby Way', 3, 2);
                        
>

How would you call the static method defined above?

Apartment.compareTwo(apartment1, apartment2);

How do you inherit from another class? Use Appartment as the child class, and BuildingUnit as the parent class

class BuildingUnit {
    //stuff here ..
}

class Apartment extends BuildingUnit{
    // Stuff here ..
}                                            
>

How do you use your constructor in your child class to set properties in your parent class?

The first call in your constructor MUST be to the parent, before you use your "this" operator.

super(<Variable1, Variable2, ...>)

What if your parent class has no variables that need to be set? How do you handle that?

JavaScript has an implicit constructor. IF your child class has a constructor, BUT your parent class has no constructor, you still MUST call super() with no arguments before using the "this" operator.

CHECK THIS OUT ... I'm not sure of this answer because of the "this" operator.

What happens when you attempt to export a Class in commonJS as the following:

exports = {
         Apartment
};
                    

You overwrite the global exports. You need to use your exports as follows: exports.Apartment = Apartment

This form is not recommended to use, as it is easily confused with the ES6 "export" keyword. So by using module.exports it's planly clear your module is a commonJS module.

What is the effect of using commonJS module.exports = Apartment

This locks us into only ever being able to export a single thing. Better to use: module.exports = { Apartment: Apartment}. Now you're setting the exports keyword as an object, rather than a literal value.

What are the best ways to export your Apartment class in commonJS?

    module.exports.Apartment = Apartment;
    module.exports.littleApartment = Apartment
    module.exports = {
        littleApartment : Apartment
    }
    module.exports = {
        Apartment
    }

                        

Note: You can export many classes, functions from a file when using the object notation module.exports = { }

Given a commonJS module named universe.js, import just the module c and the module plankLength using require() and destructuring, when the export looks as follows:

    module.exports = {
        c,
        plankLength,
        findTheUltimateAnswer,
        Universe
    };
                    

Import just the class "Universe" in commonJS using destructuring

const { Universe } = require('./universe');>

Identify import forms in commonJS and ES6

commonJS : uses require and module.exports (or export.keyName)

ES6: uses import and export

Give an example of Encapsulation

You put behavior(the methods) and that data it works on (ie instance variables) together in a class.

Describe the property of inheritance

Javascript supports of type of inheritance known as implementation inheritance through a mechanism know as prototypal inheritance.

  • Implementation inheritance = the data a methods defined on a parent class are available on objects created from classes that inherit from those parent classes
  • Prototypal inheritance = JavaScript uses prototype objects to make its implementation inheritance work not just on classes but on all objects (objects can inherit directly from other objects)/


Descript polymorphism

Polymorphism means that you can treat a variable as if it were one of its parent types ... meaning that you can use the methods of a parent class on an object of a child class.

What are the 3 Pillars of Object Oriented Programming?

  1. Encapsulation
  2. Polymorphism
  3. Inheritance
>

What does S.O.L.I.D. stand for?

  • S = Single responsibility principle
  • O = Open-closed principle
  • L = Liskov substitution principle
  • I = Interface segregation principle
  • D = Dependency Inversion principle
>

What is the Liskov substitution principle (LSP)

Any method that a class overrides from its parent class must have similar behavior with respect to the original method. If broken, it breaks the polymorphism pillar of OOP! :(

What is the Dependency Inversion Principle?

  1. A high-level module should not depend on low-level modules, but on abstractions instead.
  2. Detailed implementations should rely only on abstractions.
  3. No internal depencencies! Basically, creater new class instances OUTSIDE and pass in - do not create new class instances INSIDE.
  4. Often implemented using something called dependency injection


How do you comply with the Law of Demeter

The Law of Demeter is more of a guideline than a principle, to help reduce coupling between components.

It is often called "the one dot rule"

The easiest way to comply with the Law of Demeter is don't use more than one dot (not counting the dot after "this" (this.state.getCategory() is a-okay).

For example, the following code breaks the Law of Demeter:

What is CommonJS

CommonJS was a project with the goal to establish conventions on module ecosystem for JavaScript outside of the web browser.

How do you recognize a CommonJS script?

CommonJS can be recognized be recognized by the use of require() and module.exports

How do you recognize ESM (ES6 modules)?

By the use of import and export

Question

Answer

Question

Answer

Question

Answer

Question

Answer

Question

Answer