var
and let
: global vs block;
Prevent Object mutation
1 | function freezeObj() { |
Arrow functions
1 | var magic = function() { |
is equivalent to:1
2
3var magic = () => {
return new Date();
};
When only a single return
in func body:var magic = () => new Date();
With Params:1
2
3
4var myConcat = function(arr1, arr2) {
return arr1.concat(arr2);
};
console.log(myConcat([1, 2], [3, 4, 5]));
same:1
2var myConcat = (arr1, arr2) => arr1.concat(arr2);
console.log(myConcat([1, 2], [3, 4, 5]));
Higher order (using map
, filter
&& reduce
):1
2
3
4
5
6
7
8
9const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
const squaredIntegers = arr.filter(num => Number.isInteger(num) && num > 0).map(x => x * x);
return squaredIntegers;
};
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
map, filter, reduce
functions are mostly used w. anonymous function definitions in the form of1
arrayName.map/filter/reduce(e/(p1, p2) => blabla);
args.map()
: call func on each element inargs
, returnmapped
res;args.reduce()
: call func on all elements, return accumulated res;args.filter()
: call func on all eles, return filtered res.
Set Default params
1 | const increment = (function() { |
Rest operator (...args)
; ~ *args
in python
1 | const sum = (function() { |
is equivalent to:1
2
3
4
5
6const sum = (function() {
return function sum(...args) {
return args.reduce((a, b) => a + b, 0);
}
})();
console.log(sum(1,2,3,4));
Spread operator [...args]
: copy✅, reference❌; (make copy)
1 | const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY']; |
spread operator:1
2
3
4
5
6
7const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
(function() {
arr2 = [...arr1]; // spread operator; make a copy
arr1[0] = 'potato'
})();
console.log(arr2);
Destructing assignment {a:b} = obj
: assign object values to variables; ~ “unbox” in py/java
template:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24var voxel = {x: 3.6, y: 7.4, z: 6.54 };
// old way
var x = voxel.x; // x = 3.6
var y = voxel.y; // y = 7.4
var z = voxel.z; // z = 6.54
// { field: newVariable } = oldVar;
const { x : a, y : b, z : c } = voxel;
const AVG_TEMP = {
today: 77.5;
tomorrow: 79
};
function getTempOfTomorrow(avgTemp) {
"use strict";
// destructing
const { tomorrow: temp } = avgTemp;
return temp;
}
console.log(getTempOfTomorrow(AVG_TEMP));
nested:1
2
3
4
5
6
7
8
9
10
11
12
13
14const LOCAL_FORECAST = {
today: { min: 72, max: 83 },
tomorrow: { min: 73.3, max: 84.6 }
};
function getMaxOfTmoorrow(forecast) {
"use strict";
const {tomorrow : { max : max_tomorrow }} = forecast;
return max_tomorrow;
}
console.log(getMaxOfTmoorrow(LOCAL_FORECAST));
Destructing assign [] = arr
: assign vars from arrays;
1 | const [z, x] = [1,2,3,4,5,6]; |
Destructing assign with Rest operator
1 | const source = [1,2,3,4,5,6,7,8,9,10]; |
Destructing assign: pass an Object as param; or fields of Objects
1 | // create an object with {}; |
from above: ways to create objects in js:
create several similar objects:
new
1
2
3
4
5
6
7
8
9function person(fname, lname, age, eyecolor){
this.firstname = fname;
this.lastname = lname;
this.age = age;
this.eyecolor = eyecolor;
}
myFather = new person("John", "Doe", 50, "blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");create one object of a kind, like a singleton;
1
2
3
4
5
6
7
8var Robot = {
metal: "Titanium",
killAllHumans: function(){
alert("Exterminate!");
}
};
Robot.killAllHumans();initialize propertieis of the objects depending on other properties;
1
2
3
4
5var NewObject = {};
NewObject['property1'] = value;
NewObject['property2'] = value;
NewObject['method'] = function(){ /* function code here */ }
Anyway, {}
is used a lot; JS objects are represented in {}
.
Create Strings w. Template Literals ~ Template in Django MVT
xxxx
as code block in markdown;${object fields}
;
1 | const person = { |
1 | const result = { |
Concise Object literals declarations via Simple fields
1 | const createPerson = (name, age, gender) => { |
Create objects via Class
Old way: constructor function, new
1
2
3
4
5
6var SpaceShuttle = function(targetPlanet){
this.targetPlanet = targetPlanet;
}
var zeus = new SpaceShuttle('Jupiter');
console.log(zeus.targetPlanet)
New way:1
2
3
4
5
6
7class SpaceShuttle {
constructor(targetPlanet) {
this.targetPlanet = targetPlanet;
}
}
var zeus = new SpaceShuttle('Jupiter');
console.log(zeus.targetPlanet);
another example:1
2
3
4
5
6
7
8
9
10
11function makeClass() {
class Vegetable {
constructor(name) {
this.name = name;
}
}
return Vegetable; // return a class
}
const Vegetable = makeClass(); // create a class
const carrot = new Vegetable('carrot'); // create an object
console.log(carrot.name);
Getter, setter
1 | class Book { |
another example:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23function makeClass() {
class Thermostat {
constructor(temp) {
this._temp = 5/9 * (temp - 32);
}
get temp() {
return this._temp;
}
set temp(updatedTemp) {
this._temp = updatedTemp;
}
}
return Thermostat; // return a class
}
const Thermostat = makeClass(); // create a class
const thermos = new Thermostat(76); // create an object
let temp = thermos.temp; // object.fieldName
console.log(temp); // 24.4444
thermos.temp = 26;
temperature = thermos.temp;
console.log(temperature); // 26
`
import
Files can be imported from files that export.
- In one file
string_function.js
:export const capitalizeString = str => str.toUpperCase()
- In another file
index.js
under same path:1
2
3
4import { capitalizeString } from "./string_function"
const cap = capitalizeString("hello");
console.log(cap);
Use export
to reuse a Code block
1 | const capitalizeString = (string) => { |
create an export fallback w. export default
export default function subtract(x, y) {return x - y;}
import a default export
Suppose there is a file math_functions
1
2import subtract from "math_functions";
subtract(7, 4);
React inline styling
- styles should be wrapped up with in
{}
. - inside the
{}
is a JS object. - JS object also included in
{}
. - This will make the inline styling two
{}
. - usually JS object is written in the previous places.
- so two
{}
are not shown in the same line