December 16, 2024

JavaScript Notes By Tab

Lecture 0 Introduction to JavaScript & Web Development

0-0 A Brief Introduction to JavaScript:

  1. Three Core Technologies of the Web: HTML, CSS & JS.
  2. JavaScript is a high-level programming language.
  3. Front-end Apps: JavaScript can build Dynamic effects and Web applications in the browser with Vue etc.
  4. Back-end Apps: JavaScript also can build Web applications on web servers with Nodejs etc. for back-end apps.
  5. Native Mobile & Desktop Apps: Use JavaScript with React Native and the Ionic Framework and tools like Electron.

0-1 The Development History of JavaScript:

Course GitHub Link: Click Here

Local Path: /Developer/Web/complete-javascrip-course-master

  1. Write JavaScript code inside HTML Tags with <script></script>
  2. Wrap the JavaScript code and import it into the HTML tags <body></body> like this:
1
2
3
<body>
<script src="script.js"></script>
</body>

Lecture 1 JavaScript Basic Syntax

1-0 Values and Variables

Code commenting

1
2
3
4
5
6
7
// This is a code comment.
// Code here can not be executed.

/* This is
a multi-line
comment.
*/

Declaring a variable

1
2
3
4
// let
let variableName = "Name";
let userName = "Tab";
let PI = 3.1415;

Output to the browser

1
2
let variableName = "Name";
console.log(variableName);

The way that names variable is called camelCase Notation.

1-1 Data Types

Every value is either an object or a primitive value in JavaScript.

Basic Types and Dynamic Typing in JavaScript

Basic Types:

1
2
3
4
5
6
7
8
9
10
11
12
let javaScriptIsFun = true;
console.log(javaScriptIsFun);
console.log(typeof javaScriptIsFun);

let userAge = 18;
console.log(userAge);
console.log(typeof userAge);

let undefinedVariable;
console.log(undefinedVariable);
console.log(typeof undefinedVariable);

Dynamic Typing:

1
2
3
4
5
6
7
let javaScriptIsFun = true;
console.log(javaScriptIsFun);
console.log(typeof javaScriptIsFun);

javaScriptIsFun = "Yes!"
console.log(javaScriptIsFun);
console.log(typeof javaScriptIsFun);

Type inference in JavaScript identifiers reassigned variables and automatically changes their type based on the value.

1-2 let, const and var

Three Ways of Declaring Variables

1
2
3
let userAge = 18
const userBirthYear = 2006
var lastUserBirthYear = 2006

Without declaring variable it still worked:

1
2
userName = "Tab";
console.log(userName);

This does not create a variable in the current so-called scope, instead, JavaScript will create a porperty on the global object.

1-3 Basic Operators

What operator actually is ?

Operator basically allows us to transform values or combine multiple values.

Basic Operators

Mathematical operators

1
2
3
4
5
6
7
const now = 2024;
const ageJonas = now - 1991;
const ageTab = now - 2004;
console.log(ageJonas * 2, ageTab / 2);

// 2 ** 3 means 2^3
console.log(2 ** 3);
1
2
3
4
5
const firstName = "Yang";
const SecondName = "Tab";
const userName = secondName + firstName;
console.log(userName);
// output: TabYang
1
2
3
x++;
x+=;
x--;
1
2
console.log(1 > 2); 
// >, <, =, >=, <=
1
2
3
4
5
6
7
8
9
10
// equal sign: "=" is used to assign value to a variable.
const age = 100;

// double equals
10 == 10; //output: true
"10" == 10; // output: true

// triple equals
10 === 10; //output: true
"10" === 10;// output: false

As you know, triple equals will always check for both value and type so that it’s better and safer to use triple equals than double equals.

Operator Precedence

1
2
3
4
5
6
7
8
let x = 100 + 50 * 3
// Multiplication is done first.

let x = (100 + 50) * 3
// Operators inside the parentheses are computed first.

let x = 100 / 50 * 30
// Operators with the same precedence(like * or /) are computed from left to right.

Other circumstances: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence

1-4 Types - Strings and Template Literals

Build a sentence using strings:

1
2
3
4
5
6
7
8
const firstName = "Tab";
const job = "Coder";
const birthYear = 2004
const year = 2024

const userInfo = "I'm " + firstName + ", a" + (year - birthYear) + "years old " + job + ".";

console.log(userInfo);

String interpolation method using template literals:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const firstName = "Tab";
const job = "Coder";
const birthYear = 2004
const year = 2024

const userInfoNew = `I'm ${firstName}, a ${year - birthYear} years old ${job}.`;
console.log(userInfoNew);

console.log(`My birth year is ${birthYear}.`);

// multiple lines
console.log('String \n\
multiple \n\
lines.')

console.log(`String
Multiple
lines.`);

1-5 Types - Objects

What is Objects?

Objects are used for collections of data or collections of functions. When something is an object in JavaScript, it’s because we want to group things together.

Build An Object

1
2
3
4
5
6
7
8
// Build an object for collection that is a "person".
// object_name = {propertyName: valueName};

const person = {
firstName: "Yang",
lastName: "Tab",
age: 100,
};

Inside of the Object person, there are properties and values and they are disorder.

Access the Properties

We can use “dot notation” to access the properties.

1
2
3
4
5
6
7
8
const person = {
firstName: "Yang",
lastName: "Tab",
age: 100,
};

person.age
// output: 100

1-6 Types - Objects

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
console.log("Hello World!")

// let, const
let age = 18;
age = 19;
console.log(age); // output: 19

const birthYear = 2019;
// birthYear = 2020;
console.log(birthYear); // error!

// let score; // safe
// const userScore; // error!

// Data Types: String, Number, Boolean, null, undefined
const userName = "Tab"; // String
let userAge = 19; // Number
const birthDay = 29;
const isCool = true; // Boolean
const x = null; // 被定义为空的值
const y = undefined; // 未定义的值
let z; // Data Type is undefined

// typeof 获取值类型
console.log(typeof userName);
console.log(typeof x); // output: object (js的一个小错误), 实际为 null

console.log("My name is " + userName + ", and I am " + userAge);
console.log(`My name is ${userName} and I am ${userAge}`);

const str = "Hello World!";

// Property: length
console.log(str.length);

// Function: toUpperCase, toLowerCase, substring, split
console.log(str.toUpperCase());
console.log(str.toLowerCase());
console.log(str.substring(0, 5));
console.log(str.split(", "));

// Array
// 数组的构造函数
const numbers = new Array(1, 2, 3, 4, 5);
console.log(numbers);

const arr = ["apples", "oranges", "pears"];
console.log(arr[0]); // output: apples

let users = ["Tab", "Mike", "Lily"];
// add an element 末尾添加元素方法: push
users.push("Scarlett");
console.log(users);

// 数组头部添加元素方法:unshift
users.unshift("Zoom");
console.log(users);

// 删除末尾元素方法:pop
users.pop();
console.log(users);

// indexOf 查看元素索引值
console.log(users.indexOf("Mike"));

// 判断变量是否是数组:Array.isArray()
console.log(Array.isArray(users));
console.log(Array.isArray("Hello"));

// Object对象 键值对
const person = {
firstName: "John",
lastName: "Doe",
age: 19,
hobbies: ["Music", "Dance", "Kpop"],
address: {
street: "50 main st.",
city: "Boston",
state: "MA",
},
};

console.log(person.firstName); // output: John
console.log(person); // output: ENTRIE
console.log(person.address.city); // output: Boston

// 对象值解构
const { firstName, lastName, address: { city } } = person;
console.log(firstName);
console.log(city);

// 添加新属性
person.email = "tabyang@gmail.com";
console.log(person.email);

// 对象数组
const todos = [
{
id: 1,
text: "Take out trash",
isCompleted: true,
},
{
id: 2,
text: "Meeting with boss",
isCompleted: true,
},
{
id: 3,
text: "Dentist appt",
isCompleted: false,
},
]
console.log(todos[1].text);

// JSON
const todoJSON = JSON.stringify(todos);
console.log(todoJSON);
// output:
// [
// {
// "id": 1,
// "text": "Take out trash",
// "isCompleted": true
// },
// {
// "id": 2,
// "text": "Meeting with boss",
// "isCompleted": true
// },
// {
// "id": 3,
// "text": "Dentist appt",
// "isCompleted": false
// }
// ]

// IF
let userScore = 10;

// 考虑数据类型
if (userScore === 10) {
console.log("Score is 10");
}

// 不考虑数据类型
if (userScore == 10) {
console.log("Score is 10");
}

// if-else
const newScore = "10";
if (newScore === 10) {
console.log("YES!");
} else {
console.log("NO!");
}

// if-elseif-else
userScore = 7
if (userScore < 6) {
console.log("It is too bad!");
} else if (userScore >= 6 && userScore < 8) {
console.log("Good!");
} else {
console.log("GREAT!");
}

// 三目运算符
const level = 10;
let color = level <= 10 ? "red" : "green";
console.log(color);

// Switch
color = "blue";

switch (color) {
case "red":
console.log("Color is red.");
break;
case "green":
console.log("Color is green.");
break;
default:
console.log("Color is Not red and green.");
}

// for
for (let i = 0; i < 10; i++) {
console.log(`Number: ${i}`);
}

// while
let i = 0;
while (i < 10) {
console.log(`Nunber: ${i}`);
i++;
}

// 循环遍历数组
const newArr = [1, 2, 3, 4, 5, 6];
for (let i = 0; i < 6; i++) {
console.log(newArr[i]);
}

let k = 0;
while (k < 6) {
console.log(newArr[k]);
k++;
}

for (let todo of todos) {
console.log(todo.id);
}

About this Post

This post is written by Tab Yang, licensed under CC BY-NC 4.0.

#note#web#js