Adv Conc- Modules, Exceptions, Garbage Collection, Side effects/Pure Functions Flashcards
What are the benefits of using modules? (3 things)
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.
Import a module managed by npm
const readline = require(‘readline-sync’);
let choice = readline.question(“Do you want to run this program? (y/n)”);
CommonJS modules are compatile with browsers
t or f
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.
Export and import a module
module.exports = anObject
let pear = require(“./CodeTester1”);
// it needs the path
hat 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);
The last module.export to get processed is processed
export a module (for use in a compatible browser) (2 ways)
export let variable = primitive or object
or
export {variable}
import a module (for use in a compatible browser)
import { variableNameFromOtherFile } from “./filePathAndName.ext”
import multiple modules in one line (for use in a compatible browser)
import { variableName1, variableName2 } from “./filePathAndName.ext”
Import a module and change the variable name (for use in a compatible browser)
import { variableName1 as newVar1, variableName2 } from “./filePathAndName.ext”
Import all modules (for use in a compatible browser) and access them
File1.js
export function foo() {
console.log(1);
}
File2.js
import * as FooModule from “./File1”;
FooModule.foo(); // 1
What is this called?
File1.js
export function foo() {
console.log(1);
}
File2.js
import * as FooModule from “./File1”;
FooModule.foo(); // 1
Namespace import.
While using Namespace imports is possible, it is more common and preferred to use Named imports for importing specific declarations.
How many default exports are allowed per file
1
Do default export and import (for use in a compatible browser
bar.js
function bar() {
console.log(2);
}
export default bar;
otherfile.js
import bar from “./bar”;
bar(); // 2
Do default export and import and changed the name (for use in a compatible browser
bar.js
function bar() {
console.log(2);
}
export default bar;
otherfile.js
import renamedBar from “./bar”;
renamedBar(); // 2
Do default export and import and changed the name
Also import a non default module
(for use in a compatible browser)
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