-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcheatsheet.js
421 lines (332 loc) · 9.34 KB
/
cheatsheet.js
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//
// === Basics ===
// Semicolons are optional - recommended best practice is to use them.
//
const name = 'bob'; // string - either single-quote or double-quote. Stick to one of them.
const age = 23; // number (note: there is no int, double, float, etc. Just "number")
const isImpressed = false; // bool
const nada = undefined; // undefined aka nothing at all
const alsoNada = null; // null is nothing, but also something (it's a value). Yeah, it's weird...
// Note regarding null and undefined: If you want to ensure a value is set,
// you need to check for both null AND undefined. If you just check for null,
// you'll still get an exception if the value is undefined.
//
// === Objects ===
//
const person2 = {
name: 'john',
height: 190
};
// Object with nested object
const janeDoe = {
name: 'jane',
contactInfo: {
email: '[email protected]'
phone: '11223344'
}
};
//
// === Arrays ===
//
// An array of strings
const fruits = ['apple', 'orange', 'banana'];
// An array of car objects
const cars = [
{ make: 'ford', model: 'focus', colour: 'red' },
{ make: 'toyota', model: 'corolla', colour: 'black' },
{ make: 'mercedes', model: 'glc', colour: 'white' }
];
// Complex object with arrays and objects
const norway = {
regions: [
{
name: 'Vestland',
population: 638821,
counties: [
{ name: 'Bergen' },
{ name: 'Dale' }
]
},
{
name: 'Rogaland',
population: 482645,
counties: [
{ name: 'Stavanger' },
{ name: 'Haugesund' }
]
}
]
};
const dale = norway.regions[0].counties[1].name;
const stavanger = norway.regions[1].counties[0].name;
//
// Array.push and Array.pop
//
const animals = ['pigs', 'goats', 'sheep'];
animals.push('cows');
console.log(animals); // ['pigs', 'goats', 'sheep', 'cows']
animals.pop();
console.log(animals); // ['pigs', 'goats', 'sheep']
//
// Array.map
//
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1); // [2, 8, 18, 32]
//
// Array.filter
//
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result); // ['exuberant', 'destruction', 'present']
//
// Array.reduce
//
const array2 = [1, 2, 3, 4];
const sum = (accumulatedSum, arrayItem) => accumulatedSum + arrayItem;
const sumOfArray = array2.reduce(sum);
console.log(sumOfArray); // 10
//
// Array.find
//
const array3 = [5, 12, 8, 130, 44];
const found = array3.find(element => element > 10);
console.log(found); // 12
//
// === Destructuring ===
//
// Destructure array
const cities = ['Bergen', 'Oslo', 'Trondheim', 'Kristiansand'];
const [ firstCity ] = cities;
console.log(firstCity); // Bergen
const [ , ...restOfTheCities ] = cities;
console.log(restOfTheCities); // ['Oslo', 'Trondheim', 'Kristiansand']
// Destructure object
const city = {
name: 'Stavanger',
population: 285900,
municipality: 'Vestland',
country: 'Norway',
website: 'https://www.bergen.kommune.no'
};
const { population, website } = city;
console.log(population); // 285900
console.log(website); // 'https://www.bergen.kommune.no'
// Destructuring complex objects by combining array and object destructuring
const norway2 = {
regions: [
{
name: 'Vestland',
population: 638821,
counties: [
{ name: 'Bergen' },
{ name: 'Dale' }
]
},
{
name: 'Rogaland',
population: 482645,
counties: [
{ name: 'Stavanger' },
{ name: 'Haugesund' }
]
}
]
};
const { regions: [ { name: firstRegionName }] } = norway2;
console.log(firstRegionName); // 'Vestland'
const { regions: [ , ...{ name: lastRegionName }] } = norway2;
console.log(lastRegionName); 'Rogaland'
const { regions: [ , ...{ counties: [, lastRegionLastCounty] }] } = norway2;
//
// === Object/array spread ===
// Spread is a neat way of copying and merging
// Array spread
const array = [1, 2, 3];
const newArray = [-1, 0, ...array]; // [-1, 0, 1, 2, 3]
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
const arr3 = [...arr1, ...arr2]; // [0, 1, 2, 3, 4, 5]
// Object spread
const person = {
firstName: 'Ola',
lastName: 'Nordmann'
}
;
const newPerson = {
...person,
age: 20,
}; // { firstName: 'Ola', lastName: 'Nordmann', age:20 }
//
// === Functions ===
// Functions are first-class citizens in JavaScript and is the encapsulation/scoping
// boundary equal to a class in Java/C#
//
// There are two ways of defining a function:
// Assign an anonymous function (it has no name) to the variable sayHello:
// Anonymous functions are also called function expressions
const sayHello = function(){
alert('Hello!');
}
// Or:
// The named function sayHelloWorld:
function sayHelloWorld(){
alert('Hello World!');
}
// There are differences in how these two forms are treated behind the scenes,
// but for now just use the second version to avoid some quirks.
// Function with two parameters (note: no type constraint):
function greeter(name, sender) {
return 'Greetings from ' + sender + ', ' + name;
}
// Even though there are two parameters to a function, you can pass as few or
// as many as you want...
greeter('bob'); // <- only one param = still valid
// This will leave the second parameter as undefined, aka nothing at all.
// JavaScript thinks is ok until you do something with the second parameter inside the function
// Immediately Invoked Function Expression (IIFE):
// We often use this to prevent global scope sharing (having variables globally accessible)
// and to start initialization logic that runs without having to do a action
(function(){
}()); // <- Invokes itself
// Functions can nest functions...
(function(){
function hello(){
function world(){
return 'world';
}
return 'hello' + world();
}
}());
// Functions can be passed as arguments to functions...
(function(){
function world(){
return 'world';
}
function hello(worldFunction){
return 'hello' + worldFunction();
}
const helloWorld = hello(world);
}());
// Encapsulation/closure and "this"
(function(){
function Person(firstName, lastName, age){
this.fullName = firstName + ' ' + lastName;
this.age = age;
this.greet = function(){
alert('Greetings, ' + fullName); // TODO: <- name is not available
}
}
const bob = new Person('bob', 'bobson', 30); // When a function is supposed to be newed/instantiated, the common convention is to use uppercase first letter.
bob.greet();
}());
//
// === arrow functions
//
// Arrow function syntax is a compact alternative to a function expression /
// named function:
// Traditional anonymus function
const bob = function (a) {
return a + 100;
}
// Traditional Function
function bob2(a) {
return a + 100;
}
// Arrow Function (no braces and no return means the return is implied)
const bob3 = (a) => a + 100;
// Arrow function with body braces and explicit return statement
const bob4 = (a) => {
// do stuff
return a + 100;
};
// Arrow function with single argument needs no argument parentheses
const bob5 = a => a + 100;
// Arrow Function with multiple arguments needs argument parentheses
const bob6 = (a, b) => a + 100 + b;
//
// === var / const / let ===
//
// var is scoped to the entire function, module or globally (depending on
// where it is declared)
var foo = 1;
// let is scoped to the block it is declared in, where a block is delimited
// by a pair of braces: {}
// Examples of blocks include for-loops are if-statements.
let bar = 2;
// const is like let, except that values cannot be changed through re-assignment
const fooBar = 3;
fooBar = 4; // Will throw an error: TypeError: invalid assignment to const `fooBar'
// Recommentation: Never use var, use let or const instead.
// Scoping examples using var and let
const varTest = () => {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
const letTest = () => {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
//
// === Loops ===
//
// While:
while (learningIsFun){
learnMore++;
};
// Do/While:
do {
learnMore++;
} while(learningIsFun)
// For-loop:
for (const i = 0; i < items.length; i++){
console.log(items[i]);
}
// For of loop:
const cars2 = ['Volkswagen', 'Ferrari', 'Ford'];
for(const car of cars2) {
console.log(car); // 0 1 2
}
// For-in loop:
const car = {
model: 'Passat',
make: 'Volkswagen'
}
for(const carProperty in car) {
console.log(carProperty); // 'model' 'make'
}
//
// === Conditionals ===
//
// Switch:
switch (name){
case 'bob':
greetBob();
break;
case 'sarah':
greetSarah();
break;
default:
greetAnon();
};
// If:
if (name === 'bob'){
greetBob();
} else if (name === 'sarah'){
greetSarah();
} else {
greetAnon();
}
//
// === Equality check quirks ===
//
// TL;DR: Always use === and !== instead of == and !=
// http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons