Statement, Operations
Variable, Const, Types
1
Outline
• Expressions, Operators and Statements
• Variables, Values, Types, Operators
• Guidelines, Best Practice
• Annexes
2
Expressions, Operations and Statements
• 1; • Control flow
• !false; • if … else …
• switch … case …
• x = 2 * (3 + 4);
• Loops
• [Link]([Link](2, 4) + 100); • for (… ; ….; …) …
• while … do …
• do … while …
• break
3
Variable: What is it? Why we need it?
• A variable in programming is a placeholder for a value that can be changed during the
execution of a program.
• A constant in programming is a placeholder for a value that can NOT be changed during
the execution of a program.
• There are typically 4 components to define a variable:
• Name: to invoke the variable
• Value: the value of the variable
Name Value
• Address: the memory slot for the variable
• Type: to tell the computer whether it is ‘A’ or 65! (number) myVariable = 65
Address
Type
4
JavaScript Variable
• A JavaScript variable can hold any • JS variables must be identified width unique
type of data. names.
• In JavaScript, one should not worry
about variable address
• JS does not allow working directly with
memory address Identifier (variable name) Value
• JavaScript is Typeless:
(number) myVariable = 65
• There is no way to declare a variable
type.
• The value decides the type of variable Address
Type
• A variable can have different values, of
different type in one program
5
Variable: Recommended naming convention
• Rules for unique identifiers are: • Recomanded naming convention
• Names can contain letters, digits, _, • myVarAtJavascript: first letter
and $. lowercase, every other starting letters
• Names must begin with a letter. uppercase (camelCase)
• Names can also begin with $ and _. • _myVar: for variables that should not be
• Names are case sensitive. accessed outside
• Reserved words (like JavaScript • $myVar: for special purpose variables
keywords) cannot be used. • MY_CONST: Uppercase for constants
• Get meaning full name! (no X, Y, Z …
studentAge, studentName, etc.)
See also:
• Variable Names
• Naming conventions
6
Datatypes (kiểu)
Types are dynamic
Same variable can be used to hold different data types
• Primitive type • Numbers
• String • All JS numbers are stored as decimal numbers (64-bit floating point)
• Number • Special numbers: infinity, -infinity, NaN
• BigInt • BigInt
• Boolean • To store integer values that are too big to be represented by a normal JS number
• Undefined
• Booleans
• Null
• true or false
• Symbol
• Imprimitive type • Arrays
• Arrays • Objects
• Object • Built-objects: objects, arrays, dates, maps, sets, intarrays, floatarrays, promises, …
• User defined objects
7
Datatype examples
8
Automatic type conversion
• Type coercion
9
String
• A String is any combination of characters
• Must be surrounded by quotes:
let str1 = ‘Hello’
let str2 = “World”
let phrase = `Say ${str1} ${str2}` => Say Hello World
• String in JS can be compared, added, subtracted, etc.
• Math is safe in JS
10
Boolean
• A logical value that is either Value Meaning
true or false false The keyword false
• Often use in a conditional 0 The number zero
statement -0 The number negative zero
• E.g if (isANumber) 0n BigInt, 0n is falsy.
[Link](isANumber)
"" Empty string value
• There are only 8 false values JS
null null - the absence of any value
• Everything else is true undefined undefined - the primitive value
NaN NaN - not a number
11
Null and Undefined
• null and undefined are special type • Similarities:
in JavaScript • Both are false
• null: • Both can be assigned to variables
• An empty or non-existent value let a = null
• Must be assigned or initialized let b = undefined
let a = null; • Differences
[Link](a);// null • null has object type
• undefined • undefined has undefined type
• Typically mean a variable is declared
but not initialized • It is believed null and undefined is
let b; an implementation mistake of JS
[Link](b);// undefined
12
JavaScript Object
• Can be seen as a complex variable with properties and methods
• Properties are named Values
• Methods:
• actions that can be performed on
objects
• functions stored as Properties
• Object declaration
• Using an Object Literal
• Using the new keyword
• Using an Object Constructor
• Objects are Mutable
• x is not a copy of person
• x is person
13
JSON
• JSON stands for JavaScript Object • JavaScript Object to JSON
Notation let jsonObject =
• Not a JavaScript Object [Link](jsObject)
• Language independent • JSON to Javascript Object
• Basically text Let jsObject =
• Mostly use to exchange data [Link](jsonObject)
between browser and server.
• Q? What are differences
between JSON and JS Object?
(practice)
14
Array
• An Object which allows store keyed collections of values
• Declaration
• let arr = [] => most of the time
• let fruits = [“Apple”, “Orange”, “Plum”]
• let mixedArr = [“Hello”, “World”, 1, false]
• let arr = new Array()
• Accessing array elements:
• Array elements are indexed, starting with zero
[Link](mixedArr[0]) // Hello
Index 0 1 2 3
mixedArr “Hello” “World” 1 false
15
When to Use var, let, const?
• let was introduced in 2015 to fix some var issues
• Before 2015, var is the only way to declare a variable in JS
• After that, using let is more secure
• Multiple differences between var and let (will be discussed later)
• Read more: [Link]
• Using let is recommended!
• Const should be used for constants and Objects (will be discussed
later)
• See also (When to Use var, let, or const (w3schools)?
16
Annexes: Style guide
1. Variable names 9. Use lower case filenames
2. Spaces around operators
3. Code indentation
4. Statement rules
5. Object rule
6. Line length < 80
7. Naming conventions
8. File extensions
Reference: [Link]
17
Annexes: Best practices
1. Avoid global variables conversions
2. Always declare local variables 9. Use === comparison
3. Declarations on Top [Link] parameter defaults
4. Initialize variables [Link] your switches with
5. Declare objects with const defaults
6. Declare arrays with const [Link] number, string, Boolean
as objects
7. Don’t use new Object()
[Link] using eval()
8. Beware of automatic type
Reference: [Link]
18
Annexes: Operators
• Operators
• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• String Operators
• Logical Operators
• Bitwise Operators
• Ternary Operators
• Type Operators
19
Arithmetic & Assignment Operators
• Arithmetic Operators • Assignment Operators
20
Comparison, Logical & Type Operators
• Comparison Operators • Logical Operators
• Type Operators
?:
21
Bitwise Operators
• Bit operators work on 32 bits numbers.
• Any numeric operand in the operation is converted into a 32 bit number. The result is
converted back to a JavaScript number.
22
Number
• A variable with value is a number will have type number
let myVar = 100
• myVar has a value of 100 and is of type number
[Link](typeof(myVar)) => number
• 3 special values:
• INFINITY : greater than any number
• - INFINITY : smaller than any number
• NaN : not a number
• Math is safe!
• There will be no error for math operations with variable in JS (Divided by zero,
adding a number with a non-number variable, …)
23
BigInt
• The biggest integer number in JS is 253-1 (contrary for smallest
number)
• BigInt is added to extend the range (high precision math or
cryptography)
• A BigInt is declared with letter ‘n’ to the end of an integer
const bigVar = 1234567890123456789012345678901234567890n
• BigInt is rarely needed
24
Symbol
• Represents a unique identifier
• Created using Symbol()
let id = Symbol(); // a new symbol
let id = Symbol("id"); // a new symbol with the description “id”
• Symbols are guaranteed to be unique
let id1 = Symbol("id");
let id2 = Symbol("id");
[Link](id1 == id2); // false
• Symbol is rarely used* to be discussed in related topics.
25
Hoisting
• Hoisting is JS’s default behavior of moving declarations to the top
• Variables declare anywhere in the code will be put on top
• Example:
26
Hoisting
• Can lead up to errors, bugs or strange behavior
• let, const are hoisted but not initialized => safer to use
• const: requires variables to be initialized at declaration
• let: variables should be initialized at declaration,
otherwise undefined is assigned
• It is a good practice to put all variables declaration on
top of a program, function or scope.
27
Branch statement: If
• Similar to C/C++ syntax Best practice:
if (<condition>) <statement> Should carefully handle all cases of nested if – else
[else <statement>] Make a truth table
E.g., for 2 conditions:
condition1 condition2 && ||
True True True True
True False False True
False True False True
False False False False
? : operator
28
Switch statement
• Can be used to replace multiple if statements
• Use strict equality “===” for comparison
switch(x) {
case 'value1': // if (x === 'value1’)
// Do Something
[break]
case 'value2': // if (x === 'value2’)
// Do Something
[break]
default:
...
}
29
Break statement
• Break statement in each “case” is optional.
• If there is break statement:
• If the case is true, execute the action and stop.
• If there is NOT break statement:
• If the case is true, execute the action and continue to next case
(regardless of the next is true or false)
• Only stop when a break statement or the default case is reached.
30
Loops
• for - loops through a block of code a number of times
• for/in - loops through the properties of an object
• for/of - loops through the values of an iterable object
(arrays, strings, maps, nodeLists, …)
• while - loops through a block of code while a specified condition
is true
• do/while - also loops through a block of code while a specified
condition is true
31
Loops
• for/in - loops through the properties of • Do not use for in over an Array if the
an object index order is important.
• The index order is implementation-
dependent, and array values may not be
accessed in the order you expect.
• It is better to use a for loop, a for of loop,
or [Link]() when the order is
important.
32
Foreach
• A special version of for loop in javascript
• A method of Javascript array
• Cannot break or exit foreach loop early!
let students= ["John", "Pete", "Alice"]
[Link]( function(student){
[Link](student)
})
33
While loop
• Similar to for loop • Similar to while loop but the condition is
• Step is usually put inside the loop body checked after body loop execution
while (condition) { do {
// loop body // loop body
} } while (condition);
let i = 0;
let i = 0;
while (i < 3) {
do {
[Link]( i );
alert( i );
i++;
i++;
}
} while (i < 3);
34
Break vs Continue
• Break statement is used to exit the loop • Continue statement breaks one
early when certain condition is met iteration (in the loop), if a
• Apply for: For, While, Do While loops. specified condition occurs, and
continues with the next iteration
in the loop.
let sum = 0; let sum = 0;
let value = 0; let value = 0;
while (true) { while (true) {
let value += 1; let value += 1;
if (value == 5) break; // (*) if (value == 5) continue; // (*)
sum += value; sum += value;
} }
alert( 'Sum: ' + sum ); alert( 'Sum: ' + sum );
35
Bài tập
1. Nhập các hệ số a, b, c và giải phương trình bậc 2
2. Tính tổng nghịch đảo các số chẵn từ 2 tới 100: 1/2+1/4+1/6+…+1/100
3. Nhập một dãy số và tính giá trị trung bình
4. Viết lại câu lệnh sau dùng while
for (A; B; C) do_something();
5. Tính quãng đường đi được của một vật rơi tự do tại các thời điểm t = 1,2, 3,…, 20s
6. Vẫn bài toán trên, nhập thêm độ cao ban đầu, chỉ tính tới thời điểm mà vật chạm đất
36
Kiến thức cần nắm
• Phân loại câu lệnh rẽ nhánh và câu lệnh lặp
• Sử dụng được lệnh if, switch, while … do, do … while và for
• Nắm được break trong switch
• Nắm được break và continue trong các lệnh lặp
• Phân biệt và biết cách lựa chọn khi nào sử dụng if khi nào sử dụng switch
• Phân biệt lệnh logic và lệnh trên bit
• Biết và hiểu cách sử dụng giá trị nguyên như giá trị kiểu logic
• Chú ý khi sử dụng toán tử / với số nguyên
37