Adv Conc- Modules, Exceptions, Garbage Collection, Side effects/Pure Functions Flashcards

1
Q

What are the benefits of using modules? (3 things)

A

If a program is contained entirely in one file, even just 100 lines of code can take time to understand fully. Splitting the program up is easier to understand each component.

Working on a program as a team is easier with multiple files.

You have to put in more work to encapsulate and make private data properly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Import a module managed by npm

A

const readline = require(‘readline-sync’);
let choice = readline.question(“Do you want to run this program? (y/n)”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

CommonJS modules are compatile with browsers
t or f

A

Browsers don’t natively support CommonJS modules, but you can use a transpiler like Babel to transpile code that uses CommonJS modules into a format that can be used by browsers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Export and import a module

A

module.exports = anObject

let pear = require(“./CodeTester1”);
// it needs the path

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What happens if you have multiple exports?

let apple = {
a: 1,
}
let orange = {
a: 2,
}
module.exports = apple;
module.exports = orange;

let pear = require(“./CodeTester1”);
console.log(pear.a); // 2

A

The last module.export to get processed is processed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

export a module (for use in a compatible browser)

A

export let variable = primitive or object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

import a module (for use in a compatible browser)

A

import { variableNameFromOtherFile } from “./filePathAndName.ext”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

import multiple modules in one line (for use in a compatible browser)

A

import { variableName1, variableName2 } from “./filePathAndName.ext”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Import a module and change the variable name (for use in a compatible browser)

A

import { variableName1 as newVar1, variableName2 } from “./filePathAndName.ext”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Import all modules (for use in a compatible browser) and access them

A

File1.js
export function foo() {
console.log(1);
}

File2.js
import * as FooModule from “./File1”;
FooModule.foo(); // 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is this called?

File1.js
export function foo() {
console.log(1);
}

File2.js
import * as FooModule from “./File1”;
FooModule.foo(); // 1

A

Namespace import.

While using Namespace imports is possible, it is more common and preferred to use Named imports for importing specific declarations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How many default exports are allowed per file

A

1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Do default export and import (for use in a compatible browser

A

bar.js
function bar() {
console.log(2);
}
export default bar;

otherfile.js
import bar from “./bar”;
bar(); // 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Do default export and import and changed the name (for use in a compatible browser

A

bar.js
function bar() {
console.log(2);
}
export default bar;

otherfile.js
import renamedBar from “./bar”;
renamedBar(); // 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Do default export and import and changed the name
Also import a non default module
(for use in a compatible browser)

A

utils.js
export function foo() {
console.log(1);
}
function bar() {
console.log(2);
}
export default bar;

otherfile.js
import renamedBar, { foo } from “./utils.js”;
foo(); // 1
renamedBar(); // 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

import and export are usually only compatible in browser.

Do it in node and make it compatible (2 ways)

A

change the file names to .mjs

Alternatively, a more preferred method is to add “type”: “module” to the package.json file. This enables ES6 modules and the files can retain the .js extension.

//package.json
{
“name”: “index”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“type”: “module”,
“scripts”: {
“test”: “echo "Error: no test specified" && exit 1”
},
“keywords”: [],
“author”: “”,
“license”: “ISC”
}

17
Q

Create a custom error

A

throw new Error(“Divide by zero!”);

18
Q

Catch and error and do a block

A

try {
} catch(errorObject) {
}

19
Q

With a try catch statement, have it only do something if the error is of a certain kind

A

function divideOneBy(divisor) {
try {
let result = div(1, divisor);
console.log(result);
} catch (error) {
if (error instanceof DivideByZeroError) {
console.log(${error.message} ignored);
}
}
}

divideOneBy(1); // 1
divideOneBy(0); // Divide by zero! ignored

20
Q

With a try catch statement, have it only do something if the error is of a certain kind

If it’s another kind, let that error throw

A

function divideOneBy(divisor) {
try {
let result = div(1, divisor);
console.log(result);
} catch (error) {
if (error instanceof DivideByZeroError) {
console.log(${error.message} ignored);
} else {
throw error;
}
}
}

divideOneBy(1); // 1
divideOneBy(0); // Divide by zero! ignored

21
Q

What Happens When A Program Throws An Exception

A
  1. js goes back to look for a try block to see if it contains the code. Looks back at all the blocks, if none are try blocks, throws the error
  2. if it finds a try block, it exist the try block (without executing anymore code) and executes the catch block
  3. If the catch block re-throws the exception, it again resumes as before, looking for another try block.
22
Q

What happens with this:
try {
console.log(1);
a = b;
console.log(2);
} catch(error) {
console.log(3);
}

A

1
3

23
Q

YOu should use exceptions for flow control
“if this throws an error, then do this other code”
t or f

A

F

24
Q

What’s the idea of “ask forgiveness” in error throwing

A

– Computer programming pioneer Admiral Grace Hopper

Exceptions are sometimes likened to the “ask forgiveness” approach to error handling. Rather than asking whether we can do something, we just go ahead and try it. If an exception does occur, then we have to ask forgiveness – handle the exception or just accept the cost of an error.

In contrast to the “ask forgiveness” approach, the “get permission” approach involves determining beforehand whether something is going to work. For instance, if we expect a user to input a number, we can test whether they really did enter a number before we try to use it as a number. This is often harder to do than allowing an exception to be raised, but once permission is granted, we know things will work.

25
Q

In general, an exception handler in a catch block should do as little as possible. But you can… (5 things)

A

Ignore the exception.

Return an error value (e.g., undefined, null) to the calling function.

Set a flag that the program can test after the handler finishes running.

Log a simple error message

Throw another exception with an explicit throw statement. (but you can explicitly set another exception. Just don’t do anything like try to read a file that might now be there)

26
Q

What makes a function have side effects? (5 things)

A

It reassigns any non-local variable.

It mutates the value of any object referenced by a non-local variable.

It reads from or writes to any data entity (files, network connections, etc.) that is non-local to your program.

It raises an exception.

It calls another function that has any side effects that are not confined to the current function. For instance, if you call a function that mutates an argument, but that argument is local to the calling function, then it isn’t a side effect. (See the example with sort later in this assignment.)

27
Q

we will often talk about side effects as a general characteristic of some functions. If the function can have side effects when used as intended, then we say the function itself has side effects. In practice, functions that have side effects have them regardless of what arguments are passed in.

What makes a function not used as intended? (3 things)

A

If a required argument is omitted, the function isn’t being used as intended.

If you pass an array to a function that expects a number, the function isn’t being used as intended.

If you call a function before you’ve done any required preparations (such as opening a connection to a remote server), the function isn’t being used as intended.

28
Q

Does this have side effects?

function sortCopy(arrayOfNumbers) {
arrayOfNumbers = arrayOfNumbers.slice(); // creates a copy of an array
arrayOfNumbers.sort((a, b) => a - b); // sort has local side effects
return arrayOfNumbers; // function has no side effect
}

A

no

29
Q

do either of these have side effects?

[1, 2, 3].map(number => 2 * number);
[1, 2, 3].map(number => {
console.log(number);
return 2 * number;
});

A

[1, 2, 3].map(number => 2 * number);
[1, 2, 3].map(number => {
console.log(number);
return 2 * number;
});

30
Q

Does this have side effects?

function divideBy(numerator, denominator) {
try {
if (denominator === 0) {
throw new Error(“Divide by zero!”); // side effect: raises an exception
}
} catch (error) {
return undefined;
}

return numerator / denominator;
}

A

No, the error was handled

31
Q

Does this have side effects?
function divideBy(numerator, denominator) {
try {
if (denominator === 0) {
throw new Error(“Divide by zero!”); // side effect: raises an exception
}
} catch (error) {
console.log(error.message);
return undefined;
}

return numerator / denominator;
}

A

yes, the catch block has a side effect

32
Q

Does Math.random have side effects?

A

Math.random() has a side effect (it changes the state of the random number generator).

33
Q

What makes a pure function? (2 things)

A

Have no side effects.

Given the same set of arguments, the function always returns the same value during the function’s lifetime. This rule implies that the return value of a pure function depends solely on its arguments.

The consistent return value is possibly the most important feature of pure functions. The fact that the return value is dependent solely on the arguments implies that nothing else in the program can influence the function during the function’s lifetime.

34
Q

What s a functions lifetime?

A

A function’s lifetime begins when the function is created. It ends when the function is destroyed.

35
Q

Whats the benefit of pure functions?

A

A big benefit of pure functions is that the consistent return value and lack of side effects make them easy to test. Since they are effectively isolated from the rest of the program, you don’t have to worry about what happens elsewhere. Nothing outside of the function can have any effect on it. Nothing in the function can have any impact on the rest of the program. This is very convenient and helpful when testing.

36
Q

Update one object’s properties with the properties of another.
Exampel:
let obj1 = {
a: 1,
b: 2,
c: 3,
}

let obj2 = {
b: 1312,
}

we want b of obj1 to be 1312

A

Object.assign(obj1, obj2)

37
Q

Remove an object property

A

delete obj1.property