forked from kbroman/ProgrammingNotes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavascript.txt
More file actions
81 lines (60 loc) · 1.8 KB
/
javascript.txt
File metadata and controls
81 lines (60 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// JavaScript ES6 notes
// Destructuring assignment
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
var a,b;
[a,b] = [1,2];
var chartOpts = {h:300, linecolor:"slateblue"};
var h, w, fill, linecolor;
({h=900, w=600, fill, linecolor} = chartOpts);
// h assigned chartOpts.h
// w assigned default value, 600
// linecolor assigned chartOpts.linecolor
// fill is undefined
// Template strings
var x = 30;
y = `x + 20 = ${x+20}`;
// need to use backticks and ${}
// loops
while(1) { }
for(let i=0; i<x.length; i++) {}
for(i in x) {} // loop over keys in object, or indices of array
for(xv of x) {} // loop over values of array
// break, continue
x = [1,3,9]
for(i of x) {}
for(xv in x) {}
y = {a:5, b:10, c:11}
for(key in y) {} // can't use for(key of y) {}
// .call, .apply
// .call
// call a function as if it were a method for the provided object
function greet() { return `Hello, my name is ${this.name}.`; }
greet.call({name: "Fisher"});
function update(birthYear, occupation) {
this.birthYear = birthYear;
this.occupation = occupation;
}
bruce = { name: "Bruce" }
update.call(bruce, 1969, "statistician");
// .apply is like .call, but taking extra args as an array
update.apply(bruce, [1972, "writer"]);
// you can use this to pass an array to Math.min or Math.max
x = [1, 23, -3, 4, 5]
Math.min.apply(null, x)
Math.max.apply(null, x)
// can also use ... (the "spread" operator)
Math.min(...x)
Math.max(...x)
// .bind permanently attaches an object (as "this") to a function
updateBruce = update.bind(bruce)
/////////////////////////////////
// ES6
/////////////////////////////////
// .map, .filter with =>
x = [1,3,0,-2]
x.filter( d => d > 0 )
x.map( d => d**2 )
// template literals (expressions in strings)
// backticks and ${}
x = 5
y = `blah: ${x}`