Skip to content
tnhoang 🦁

Javascript in short

Programming1 min read

Speaking Javascript - Dr. Axel Rauschmayer

Array

1// Array are maps not tuples
2// 1. Array has hole
3const arr = []
4arr[1] = "1" // arr => [, "1"]
5// 2. Array has props
6arr.foo = 123
7
8
9// ---------------------
10// Array indices
11// Indices that are out of range are treated as property key
12arr[-1] = 'a';
13arr[4294967296] = 'b';
14// arr => []
15// arr['-1'] => 'a'
16// arr['4294967296'] => 'b'
17
18// ---------------------
19// Delete array elements will create hole
20const arr = ['a', 'b']
21delete arr[1]
22// arr => ['a', ]
23
24// So should use splice(Destructive) to not create hole
25arr.splice(1,1)
26// arr => ['a']
27
28// ---------------------
29// Methods that check/skip holes
30// Check
31.join, sort
32
33// Skip
34.forEach, every/some, map, filter, for in
35// Note: `in` operator will loop through property keys and indices
36const arr = [1];
37arr.foo = 'bar';
38for (const key in arr) {
39 console.log(key); // 1, foo
40}
41
42// ---------------------
43// Array prototype methods
44
45// Add/Remove elements(Destructive)
46arr.shift/unshift/pop/push/splice()
47// Sorting/Reversing elements(Destructive)
48arr.reverse/sort()
49
50// Concatenating/Slicing/Joining elements(NonDestructive)
51arr.concat/slice/join()
52// Search(NonDestructive)
53arr.indexOf/lastIndexOf()
54// Iteration(NonDestructive)
55arr.forEach/every/some()
56
57// Transformation(NonDestructive)
58arr.map/filter()
59// Reduction(NonDestructive)
60arr.reduce()

Loop

1// Normal for
2for (let i = 0; i < arr.length; i++) {
3 const element = arr[i];
4}
5
6// For-in: loop through any object
7for (let key in arr) {
8}
9
10// For-of: loop through only iterable object
11for (let key of Object.keys(o)) {
12}

String

1// Useful functions
2s.split(",");
3s.slice((start = 1), (end = 2));
4s.trim();
5s.toLowerCase();
6s.toUpperCase();
7s.indexOf(",");
8s.lastIndexOf(",");
9s.replace("a", "b");

Number

1// Check NaN
2Number.isNaN(x)
3
4// Converting
5Number(undefined) => NaN
6Number(null) => 0
7Number(NaN) => NaN
8Number(false) => 0
9Number('3.14') => 3.14
10Number(o: Object) => Call ToPrimitive

Boolean

1// Converting
2Boolean(null, undefined, NaN, 0, ""); // => false
3Boolean({}); // => true for any object

Occurences of null

1document.getElementById("foo"); // null

Occurences of NaN

1// When converting variable to number
20 / 0; // NaN
3Infinity - Infinity; // NaN
4Math.sqrt(-1); // NaN
5parseInt("foo"); // NaN

Occurences of undefined

1// Uninit variable
2let a; // undefined
3
4// Missing params
5function foo(a, b) {
6 console.log(b); // undefined
7}
8
9// Object access nonexistence prop
10const o = {};
11console.log(o.a); // undefined
12
13// Function with no return
14function foo() {}
15console.log(foo()); // undefined