JavaScript ranks first place in the most popular technologies at Stack Overflow for year 2020
Where does JavaScript code run?
JavaScript Engine in browsers (originally for frontend)
FireFox: SpiderMonkey
Chrome: v8
Node (runtime environment for backend)
a C++ program include Google’s v8 JavaScript engine
Difference between ECMAScript & JavaScript
ECMAScript:
specification
JavaScript
programming language
Where to import the js code?
in <head> section
at the end of <body> element (Best practice)
html is parsed from top to bottom
js code always interacts with elements, need to ensure the elements already exist
Basics
Variables
store data temporarily
declare a variable var (Before ES6), let (After ES6),
by default, the value of a declared variable is undefined
rules of variable name
Cannot be a reserved keyword: let, if, var
Should be meaningful
Cannot start with a number
Cannot contain a space or hyphen
are case-sensitive
Constants
const
value cannot be changed / re-assigned
default choice if the value will not be changed, otherwise use let
Primitive / Value types:
String
Number
Boolean
Boolean
undefined
null -> clear the value of a variable
Dynamic Typing
Statically-typed: type of variable cannot be changed
Dynamically-typed: type of variable is flexible
typeof to show the type a variable
type of undefined is “undefined”
type of null is “object”
Reference Types
Object {}
Key-value pairs
Access property
Dot notation: person.name
Bracket notation: person[‘name’]
Array []
A list of elements with index
Size of the array and the type of the element in an array is dynamic
An array is an object
Function
A parameter is defined in the function
An argument is passed in to the function as the parameter
Two types of functions:
Perform a task
Calculate a value (return a value)
Operators
Arithmetic operators:
Exponential: x ** y, x to the power of y
Increment:
++x
x++
Decrement
–x
x–
Assignment operators:
x = 5;
x += 5;
x *= 2;
Comparison operators:
Relational: >, >=, <, <=
Equality: ==, !=, ===, !==
Equality operators:
Strict equality (type + value)
===
‘1’ === 1 -> false
more precise
Lose Equality (value)
==
‘1’ == 1 -> true
true == 1 -> true
Ternary / conditional operator:
x = Boolean ? A : B;
Logical operators:
AND (&&)
OR (||)
NOT (!)
Logical Operators with Non-booleans
Boolean || non-Boolean
Falsy (false)
undefined
null
0
false
”
NaN: type of NaN is ‘number’
Direction from left to right, or operator stops as soon as found a truthy (short-circuiting)
Bitwise Operator:
Bitwise OR (|)
Bitwise AND (&)
Control Flow
Conditional statements
if … else
switch … case
Loops:
For
While
Do…while
For…in:
loop through properties of an object
loop through elements in an array
For…of
better way to loop an array
// for loop (5 times)
for (let i = 0; i < 5; i++) {
code block
}
// while loop
let i = 0;
while ( i <= 5) {
statements;
i++;
}
// In comparison with for loop, the loop variable in while loop is declared externally
// do-while loop
let i = 0;
do {
statements;
i++;
} while ( i <= 5);
// Do-while loop execute at least once
// Be aware of infinite loops!
// for-in loop
for (let key in object) {
key
object[key]
}
// for-of loop
for (let color of colors) {
color
}
Break & Continue
break: jump out of loop
continue: jump to the next iteration
Exercise:
Demerit Points
Magic number : Unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants
Math.floor(): returns the largest integer less than or equal to a given number
Sum of Multiples of 3 and 5
Lines that are highly related should be together and blocks are better separated
Grade
Single responsibility principle
Objects
Basics:
The purpose of an object is to group related variables
Object-oriented programing (OOP)
The function of an object is called method
Object literal to create a function
Factory function
Better way to create an object with logic to prevent duplicated implementation
Function name is in form of camel notation
// Factory Function
function createCircle(radius) {
return {
radius: radius,
draw: function() {
...
}
}
}
// ES6
function createCircle(radius) {
return {
radius,
draw() {
...
}
}
}
const myCircle = createCircle(1);
// Call the function to create and return the new object
Constructor function
The function name is in form of Pascal notation by convention
Key word ‘key’ is a reference to the object that is executing current piece of code
// Constructor Function
function Circle(radius) {
this.radius = radius;
this.draw = function() {
...
}
}
const circle = new Circle(1);
// key word 'new'
// = Circle.call({}, 1);
// 1. create a new empty object
// 2. initial the object
// 3. return the pointer
Dynamic nature of object
Can always add new properties or remove existing ones
// Adding elements
const numbers = [3, 4];
// keyword const doesn't stop us from editing the content of the array
// End
numbers.push(5, 6);
// Beginning
numbers.unshift(1, 2);
// Middle
numbers.splice(2, 0, 'a', 'b');
// The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
// splice(start, deleteCount, item1, item2, itemN)
// Finding Elements (Primitives)
numbers.indexOf(1);
numbers.lastIndexOf(1);
numbers.includes(1);
// indexOf(searchElement[, fromIndex])
// Finding Elements (Reference)
const found = array1.find(element => element > 10);
// Arrow function
: find((element) => { ... } )
// Callback function: find(callbackFn)
// find() returns the value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
// Remove elements
// End
numbers.pop();
// pop() removes last element and returns it
// Beginning
numbers.shift();
// Middle
numbers.splice(2, 1);
// Empty an array
// Solution 1
// if there is no other reference points to the old array
numbers = [];
// Solution 2
// truncate the array
numbers.length = 0;
// Solution 3
numbers.splice(0, numbers.length);
// Solution 4 (not recommend)
while (numbers.length > 0)
numbers.pop();
// Combining and Slicing Arrays
const first = [1, 2, 3];
const second = [4, 5, 6];
const combined = first.concat(second);
// original arrays are not affected
combined.slice(2, 4);
// slice(start, end), end not included
const copy = combined.slice();
// Spread Operator
const combined = [...first, ...second];
const copy = [...combined];
// Iterating an Array
for (let number of numbers) {
...
}
numbers.forEach((number[, index]) => {
...
});
// Sorting Arrays
const numbers = [2, 3, 1];
numbers.sort();
numbers.reverse();
// Testing the elements of an array
const allPositive = numbers.every(function(value)
return value >= 0;
)
// terminates when meets a false case
const atLeastOnePositive = numbers.some(function(value)
return value >= 0;
)
// terminates when meets a true case
// Filtering an array
const filtered = numbers.filter(value => value >= 0);
// Mapping an array
const items = filtered.map(n => '<li>' + n + '</li>');
// Chaining of the methods
// Reducing an array
numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
// reduce(callbackFn[, initialValue])
Functions
Function declaration vs Expressio
// Function Declaration
function walk() {
console.log('walk');
}
// Anonymous Function Expression
let run = function() {
console.log('run');
};
// Named Function Expression
let runFunction = function run() {
console.log('run');
};
Hoisting
Function defined using function declaration can be called before it is defined because js engine moves all function declarations to the top
Arguments
Every function has an arguments object and it’s iterable
Function with varying number of parameters
The rest operator: function sum(…args) {} -> pass input as array
Rest parameter must be last formal parameter
Default parameters:
function interest(principal, rate = 3.5, years = 5) {}
parameters with default value should be last items
Getters and Setters
getters: access properties
setters: change (mutate) them
const person = {
firstName: 'A',
lastName: 'B',
get fullName() {
return `${person.firstName} ${person.lastName}`;
}
set fullName(value) {
if (typeof value !== 'string') {
throw new Error('Value is not a string.');
}
const parts = value.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
}
try {
person.fullName = null;
}
catch (e) {
console.log(e);
}
Error handling
Try and Catch
Defensive programming
error handling at the beginning of a function or a method
check validity of input
Scope
local variables take precedence over global variables
avoid global variables
Let vs Var
var -> function-scoped
the scope of the variable is not limited to the block in which it’s defined, the scope is limited to the function in which it’s defined
global variable declared with var will be attached to window object
let, const -> block-scoped
function start() {
for (let i = 0; i < 5; i++) {
console.log(i);
}
// console.log(i); i not accessible
for (var i = 0; i < 5; i++) {
console.log(i);
}
console.log(i); i is accessible
}
this keyword
this -> reference the object that is executing the current function
method -> obj
callback function inside a method, this by default is window object
function -> global (window, global)
constructor function -> obj
change this in functions
const self = this;
function.bind()
function.call()
function.apply()
arrow function -> inherit this from containing function