Modules
Quite crucial for reusability of code
Collect related functions, objects, values together
export
values for use by other scriptsimport
values from other scripts, packages
Ways of implementing
script -> directly include the script inside the browser
CommonJS -> introduced for server side modules
- synchronous load: server blocks till module is loaded
AMD -> Asynchronous Module Definition
- browser side modules
ECMAScript 6 and above:
ES6 modules
Both servers and browsers
Asynchronous load
npm
Node Package Manager
Node:
commandline interface for JS
mainly used for backend code, can also be used for testing
npm can also be used to package modules to the frontend
- "Bundle" managers -> webpack, rollup, etc
To import a JS module in HTML file
<script type="module" src="file.js"></script>
Direct one line export
export const c = 300000000;
Basic import
Note: This file must be included as type="module"
in HTML script
tag
import {c} from './path/to/file.js';
console.log(c);
Explicit named exports
function sq(x){
return x*x;
}
export const c = 300000000;
export function energy(m){
return m*sq(c);
}
Similarly, to use the above export
import {c, energy} from './path/to/file.js';
console.log(c);
console.log(energy(10));
Renaming imports
import {c as speedofLight} from './path/to/file.js';
console.log(speedofLight);
More stuff
Another way to write exports
Default export
When we import a variable, we get a read-only view of that variable, we cannot modify it's value. However, we can call a function that can modify the value of that variable.
Objects
Everything in JS is an object
Object literals
- Assign values to named parameters in object
Object methods
- Assign functions that can be called on an object
Special variable
this
Function methods
call(), apply(), bind()
object.keys(), values(), entries()
Use as dictionary
Iterators
Prototype based inheritance
Object can have a 'prototype'
Automatically get properties of parent
Single inheritance track
Class
Better syntax - still prototype based inheritance
constructor must explicitly call
super()
Multiple inheritance or Mixins
- Complex to implement
Basic object literals and methods
let x = {'a': 5, 'b': 'hi'};
console.log(x);
x.add = function(c,d){
return c + d;
}
console.log(x);
console.log(`x is of type ${typeof(x)}`);
console.log(`x.add is of type ${typeof(x)}`);
console.log(`Evaluate the function x.add(3,5) gives ${x.add(3,5)}`);
What is this
?
this
refers to the object it belongs to
Analogous to self
in Python
x.f = function(y){
return this.a + y;
}
console.log(x.f(100));
Copying an object
let x = {a: 1, b: 2};
let y = x;
x.a = 3;
In the previous case, y
will point to the same memory location as x
, hence changing anything in x
will also reflect in y
and vice versa.
So, how to copy objects?
let z = {...x};
x.a = 5;
In this case, z
gets its own copy of the object that x
had.
That's it for now folks, Thank you for reading :)