var
and let
: global vs block;
Prevent Object mutation 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 function freezeObj() { "use strict"; const MATH_CONSTANTS = { PI: 3.14 }; Object.freeze(MATH_CONSTANTS); // this prevent const object mutation try { MATH_CONSTANTS.PI = 99; } catch( ex ) { console.log(ex); } return MATH_CONSTANTS.PI; } const PI = freezeObj(); console.log(PI);
Arrow functions 1 2 3 var magic = function() { return new Date(); };
is equivalent to:
1 2 3 var magic = () => { return new Date(); };
When only a single return
in func body:var magic = () => new Date();
With Params:
1 2 3 4 var myConcat = function(arr1, arr2) { return arr1.concat(arr2); }; console.log(myConcat([1, 2], [3, 4, 5]));
same:
1 2 var 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 9 const 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 of
1 arrayName.map/filter/reduce(e/(p1, p2) => blabla);
args.map()
: call func on each element in args
, return mapped
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 2 3 4 5 6 7 const increment = (function() { return function increment(number, value = 1) { return number + value; }; })(); console.log(increment(5, 2)); console.log(increment(5));
Rest operator (...args)
; ~ *args
in python 1 2 3 4 5 6 7 const sum = (function() { return function sum(x, y, z) { const args = [x, y, z]; return args.reduce((a, b) => a + b, 0); } })(); console.log(sum(1,2,3));
is equivalent to:
1 2 3 4 5 6 const 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 2 3 4 5 6 7 const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY']; let arr2; (function() { arr2 = arr1; // reference; change arr2 would change arr1 arr1[0] = 'potato' })(); console.log(arr2);
spread operator:
1 2 3 4 5 6 7 const 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 24 var 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 14 const 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 2 3 4 5 6 7 8 9 10 11 12 13 const [z, x] = [1,2,3,4,5,6]; console.log(z, x); // 1 2 const [z, x, , y] = [1, 2, 3, 4, 5, 6]; console.log(z, x, y); // 1 2 4 let a = 8, b = 6; (() => { "use strict"; [a, b] = [b, a] })(); console.log(a); // 6 console.log(b); // 8
Destructing assign with Rest operator 1 2 3 4 5 6 7 8 9 10 const source = [1,2,3,4,5,6,7,8,9,10]; function removeFirstTwo(list) { const [ , , ...arr] = list; return arr; } const arr = removeFirstTwo(source); console.log(arr); console.log(source);
Destructing assign: pass an Object as param; or fields of Objects 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // create an object with {}; const stats = { max: 56.78, standard_deviation: 4.34, median: 34.54, mode: 23.87, min: -0.75, average: 35.85 }; // create an object in format: func(); const half = (function() { return function half({ max, min }) { // pass only desired fields return (max + min) / 2; } })(); console.log(stats); console.log(half(stats));
from above: ways to create objects in js:
create several similar objects: new
1 2 3 4 5 6 7 8 9 function 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 8 var Robot = { metal: "Titanium", killAllHumans: function(){ alert("Exterminate!"); } }; Robot.killAllHumans();
initialize propertieis of the objects depending on other properties;
1 2 3 4 5 var 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 2 3 4 5 6 7 8 9 const person = { name: "Lei", age: 999 }; const greeting = `Hello, my name is ${person.name}! I am ${person.age} years old.`; console.log(greeting);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 const result = { success: ["max-length", "no-amd", "prefer-arrow-functions"], failure: ["no-var", "var-on-top", "linebreak"], skipped: ["id-blacklist", "no-dup-keys"] }; function makeList(arr) { const resDisplayArray = []; for (let i = 0; i < arr.length; ++i) { resDisplayArray.push(`<li class="text-warning">${arr[i]}</li>`) } return resDisplayArray; } const resDisplayArray = makeList(result.failure);
Concise Object literals declarations via Simple fields 1 2 3 4 5 6 7 8 9 const createPerson = (name, age, gender) => { return { name: name, age: age, gender: gender }; }; console.log(createPerson("Lei", 999, "male"));
Create objects via Class
Old way: constructor function, new
1 2 3 4 5 6 var SpaceShuttle = function(targetPlanet){ this.targetPlanet = targetPlanet; } var zeus = new SpaceShuttle('Jupiter'); console.log(zeus.targetPlanet)
New way:
1 2 3 4 5 6 7 class 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 11 function 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 2 3 4 5 6 7 8 9 10 11 12 13 class Book { constructor(author) { this._author = author; } // getter get writer() { return this._writer; } // setter set writer(updatedAuthor) { this._author = updatedAuthor; } }
another example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 function 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 4 import { capitalizeString } from "./string_function" const cap = capitalizeString("hello"); console.log(cap);
Use export
to reuse a Code block 1 2 3 4 5 6 7 8 9 10 const capitalizeString = (string) => { return string.charAt(0).toUpperCase() + string.slice(1); } export { capitalizeString }; export const foo = "bar"; export const bar = "foo"; // now function capitalizeString, const foo, bar can be imported
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 2 import 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