-
Notifications
You must be signed in to change notification settings - Fork 22
/
main.js
215 lines (177 loc) · 5.51 KB
/
main.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
// --- Primitive data types ---
// string, number, boolean, null, undefined
const name = 'John'; // string
const age = 27; // number
const isMarried = false; // boolean
const height = 5.6; // number
const x = null;
const y = undefined;
let z;
// How to check the type of a variable?
// console.log('Type of z:', typeof z); // undefined
// console.log('Type of name:', typeof name);
// console.log('Type of age:', typeof age);
// console.log('Type of isMarried:', typeof isMarried);
// console.log('Type of height:', typeof height);
// console.log('Type of y:', typeof y);
// There are 3 ways to declare variables --> const, let and var.
// What is the difference between let and const?
// Use const when you know you will not reassign a variable,
// otherwise, use let.
// DON't use var!
const student1 = 'John';
// student1 = 'Jane'; // TypeError: Assignment to constant variable.
let student2 = 'Sam';
student2 = 'Jack'; // :)
// --- String ---
// String concatenation
// console.log("My name is " + name + " and I am " + age + " years old.");
// String Interpolation: lets you to inject variables & logic directly into a string
// console.log(`My name is ${name} and I am ${age} years old.`);
// String operations and properties
const str = "Hello World";
// console.log(`The length of str is: ${str.length}`);
// console.log('Str substring: ', str.substring(0, 5)); // From index 0 to index 4 (2nd parameter exclusive)
let nums = "1,2,3,4,5";
// console.log(nums.split(',')); // Splits string by delimiter
// --- Arrays ---
const integers = new Array(1, 2, 3, 4);
// console.log({integers});
const fruits = ['apples', 'oranges', 'bananas', 'mangoes'];
// console.table({fruits});
// console.log(`The length of fruits is ${fruits.length}`);
const mixArr = ['1', 2, true]; // Array with different data types
// console.log({mixArr});
// Accessing elements in array
// console.log(fruits[1]); // index starts at 0
// Add element to array if you know array size
fruits[4] = 'grapes';
// console.log({fruits});
// Add element to end of array if size is unknown
fruits.push('pears');
// console.log({fruits});
// fruits = []; is illegal since it is being assigned to a different array
// Add element to beginning of array
fruits.unshift('strawberries');
// console.log({fruits});
// Remove last element in array
fruits.pop();
// console.log({fruits});
// Remove from beginning of array
fruits.shift();
// console.log({fruits});
// Remove element at specific index
fruits.splice(0,0);
// console.log({fruits});
// Remove range of elements
fruits.splice(1, 3);
// console.log(fruits);
// --- Object Literals ---
// What is Object literal in JS?
// Object literal is a comma-separated list of name-value pairs
// wrapped in curly braces.
let person = {
firstName: 'John',
lastName: 'Doe',
age: 70,
hobbies: ['hiking', 'drinking', 'science', 'inventing'],
address: {
street: '123 main st',
city: 'Blacksburg',
state: 'Virginia'
}
};
// console.log({person});
// Access single value
// console.log(person.firstName);
// console.log(person.hobbies[2]);
// console.log(person.address.street);
// Destructuring - create variables
const {firstName, lastName, address: {state}} = person;
// console.log(firstName, lastName, state);
// Add property to object
person.email = '[email protected]';
// console.log(person);
// --- Better way to console.log ---
const foo = 23;
const bar = 24;
// Bad way:
// console.log(foo, bar);
// Better way:
// console.log({foo, bar});
// Alternative way:
// console.table([foo, bar]);
// --- For loops ---
const todos = [
{
id: 1,
text: 'take out trash',
isComplete: true
},
{
id: 2,
text: 'finish hw',
isComplete: false
},
{
id: 3,
text: 'meet with adviser',
isComplete: false
}
];
// Array traversal
for (let i = 0; i < todos.length; i++) {
// console.log(todos[i].text);
}
for (let todo of todos) {
// console.log(todo.id);
}
// forEach
todos.forEach(function(todo) {
// console.log(todo.text);
});
// Array map
// Creates a new array A2 by calling a function on each element in the input array A1.
const users = [
{ firstName: 'John', lastName: 'Doe'},
{ firstName: 'Sarah', lastName: 'Smith'},
{ firstName: 'Sam', lastName: 'Williams'},
];
// Old school imperative approach: use statements to mutate (aka change) state
const firstNames = [];
for(const user of users) {
firstNames.push(user.firstName);
}
// console.table([firstName]);
// Declarative approach: use function to describe state
const firstNames2 = users.map((user) => user.firstName);
// console.table([firstNames2]);
// How to merge arrays or object literal?
const person1 = {
firstName: 'John',
lastName: 'Doe',
age: 27
};
const job = {jobTitle: 'developer', company: 'companyX'};
const person1Merged = {...person1, ...job};
// console.log({person1Merged});
const tasks = ['do homework', 'grocery shopping', 'do laundry'];
const tasks1 = ['take out the trash', ...tasks];
const tasks2 = [...tasks, 'take out the trash'];
// console.log({tasks, tasks1, tasks2});
// --- Double equal sign '==' vs triple equal sign '===' ---
// '==' --> converts the type before running the comparison
const a = '23' == 23;
const b = '23' === 23;
// console.log({x, y});
// --- Functions ---
// 'function' syntax
function isEven(num) {
return num % 2 === 0;
}
// modern ES6 arrow syntax
const isEven2 = (num) => {
return num % 2 === 0;
};
// console.log('isEven():', isEven(4));
// console.log('isEven2():', isEven2(4));