Finished up to Chapter 4. JavaScript Functions

master
Jason Zhu 2021-01-19 21:12:12 +11:00
parent 5d1cc63d57
commit e0db7a67f0
23 changed files with 507 additions and 0 deletions

View File

@ -0,0 +1,16 @@
# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.148.1/containers/javascript-node/.devcontainer/base.Dockerfile
# [Choice] Node.js version: 14, 12, 10
ARG VARIANT="14-buster"
FROM mcr.microsoft.com/vscode/devcontainers/javascript-node:0-${VARIANT}
# [Optional] Uncomment this section to install additional OS packages.
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
# && apt-get -y install --no-install-recommends <your-package-list-here>
# [Optional] Uncomment if you want to install an additional version of node using nvm
# ARG EXTRA_NODE_VERSION=10
# RUN su node -c "source /usr/local/share/nvm/nvm.sh && nvm install ${EXTRA_NODE_VERSION}"
# [Optional] Uncomment if you want to install more global node modules
# RUN sudo -u node npm install -g <your-package-list-here>

View File

@ -0,0 +1,27 @@
{
"name": "Node.js",
"build": {
"dockerfile": "Dockerfile",
// Update 'VARIANT' to pick a Node version: 10, 12, 14
"args": { "VARIANT": "14" }
},
// Set *default* container specific settings.json values on container create.
"settings": {
"terminal.integrated.shell.linux": "/bin/bash"
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"dbaeumer.vscode-eslint"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
"forwardPorts": [3001],
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "yarn install",
// Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "node"
}

View File

@ -0,0 +1,76 @@
# Chapter 3: JavaScript Basics: Varaibles and Flow Control
## Booleans and Comparison Operators
Booleans in JS:
```js
let isFreezing = true;
let isBoiling = false;
```
Use comparison to evaluate to Booleans:
* **Equality Operator**: `===`
* **Not-equality Operator**: `!==`
* **Less than Operator**: `<`
* **Greater than Operator**: `>`
* **Less than or equal to Operator**: `<=`
* **Greater than or equal to Operator**: `>=`
## If Statements and ifelse statements
```js
if (condition) {
// executed if true
} else if {
// executed else if false
} else {
// executed after all justified
}
```
## Logical "And" and "Or" Operators
* Logical "And" Operator: `&&`
* Logical "Or" Operator: `||`
## Variable Scope
JS use **Lexical Scope (Static Scope)** has 2 types of scope:
* **Global Scope** = Defined outside of all code blocks
* **Local Scope** = Defined inside a local scope (e.g. function block or if stat)
In a scope you can access variables defined in that scope, or in any parent/ancestor scope.
**Variable Shadowing**: In local scope, we can difine same variable name to overwrite/shadow parent scopel
```js
let name = 'Andrew';
if (true) {
let name = 'Mike';
if (true) {
console.log(name); // => Mike
}
}
if (true) {
console.log(name); // => Andrew
}
```
Assigning variable also need take scope into consideration
**Leaked Global variable**: If a variable in local scope is not defined, it will look up that variable name in parent scope, ancestor scope, until global scope. If not found in global scope as well, JS will define it in global scope
```js
if (true) {
if (true) {
let name = 'Jan' // => JS will create a global name
console.log(name)
}
if (true) {
console.log(name) // => 'Jan' as it's leaked global variable
}
}
```

View File

@ -0,0 +1,69 @@
# Chapter 4: JavaScript Functions
## Function Basics
Simple JS function definition and invocation:
```js
// Function Definition
let greetUser = function () {
console.log('Welcome user!');
}
// Function Invocation
greetUser(); // => 'Welcome user!'
```
Simple JS function with 1 **argument** and **return**:
```js
let square = function (input) {
return input*input;
}
console.log(square(3)); // => 9
```
## Undefined and Null
* `undefined`:
* **Senario 1 (Undefined for variable)**: when variable is declared but without assigning value. JS assign `undefined` to it.
* **Senario 2 (Undefined for function arguments)**: Function argument is undefined when no value is parsed. Program hence does not crash.
* **Senario 3 (Undefined as function return default value)**: When function code does not return anything and when it's invoked. It return `undefined`.
* `null`:
* **Emptiness assigned to a varaible**: When a value is not sure and want to specify the variable is empty, developer can assign `null`.
## Multiple Arguments and Argument Defaults
Defining functions with multi-arguments:
```js
let func_name = function (arg1, arg2) {
// function body
}
```
Invoke this function:
```js
func_name(param1, param2);
```
Dafualt value of arguments can be set in function def:
```js
// Default arguments
let getScoreText = function (name = 'Anonymous', score = 0) {
console.log(name)
console.log(score)
}
getScoreText() // 'Anonymous', 0
```
## Function Scope
Local variable within function only exist in function scope
## Template Strings
**Template String** (aka **Template literals**): string literal careted using backticket
```js
`This is ${expression}`
```

View File

@ -0,0 +1,33 @@
# Chapter 7: Javascript in Browser
## Setting up a Web Server
Setting up a web server:
* Install `live-server` using `npm`:
```
npm install -g live-server
```
`live-server` have live-reloading feature.
Create a directory for the app.
In the app directory, create a `index.html` and add element in
After creating a HTML, we can view it `live-server <app-directory>` in browser
## JavaScript in Browser
* JS embedded in HTML via `<script></script>`
* Or put JS code in a separate file, then import it as `<script src="notes-app.js"></script>`
## DOM Manipulation
Use JS to manipulate HTML via **Document Object Model**, where document = HTML, object = JS object (i.e. Document is modeled using a JS object)
The JS object represent Document is `document`.
* Create an obj `p` and assign the queried obj to it. `document.querySelector('p')` select the first obj that has tag named `<p>`
* Script tag has to be after paragraph to query it
## Adding Elements via the DOM

View File

@ -0,0 +1,22 @@
let temp = 31;
let isFreezing = (temp === 31);
console.log(isFreezing);
if (isFreezing) {
console.log("It's freezing outside!")
}
// challenge area
// Create age set to your age
let age = 26;
// Calcualte is child - if they are 7 or under
let isChild = (age <= 7);
// Calculate is senior - if they are 65 or older
let isSenior = (age >= 65);
// Print is child value
console.log(isChild);
// Print is senior value
console.log(isSenior);

View File

@ -0,0 +1 @@
console.log('Hello Andrew!')

View File

@ -0,0 +1,6 @@
let temp = 65;
if (temp >= 60 && ) {
} else {
}

View File

@ -0,0 +1,14 @@
let age = 26;
let dogYears = (age + 1) / 7;
console.log(dogYears);
// Challenge area
// studentScore
let studentScore = 18;
// maxScore
let maxScore = 20;
// percent
let percent = (studentScore / maxScore) * 100;
console.log("Percent is: " + percent);

View File

@ -0,0 +1,11 @@
let varOne = "varOne";
if (true) {
varOne = "varOneNew";
console.log(varOne);
let varTwo = "varTwo";
console.log(varTwo);
}
console.log(varOne);
console.log(varTwo);

View File

@ -0,0 +1,6 @@
let city = "Canberra";
let country = "Australia";
let location = city + ', ' + country;
console.log(location);

View File

@ -0,0 +1,11 @@
let fahrenheit = 50;
// calculate celsius and store in celsius variable
// print the value
let celsius = (fahrenheit - 32) * (5/9);
console.log("Celsius: " + celsius);
// calculate kelvin value and store in variable
// print that value
let kelvin = celsius + 273.15;
console.log("Kelvin: " + kelvin);

View File

@ -0,0 +1,12 @@
// 1. You can't define a variable more than once
let petName = 'Hal'; // declare a variable and initialization
petName = 'Spot'; // Reassign variable (you cannot redeclare a variable)
console.log(petName);
// 2. There are rules related to variable names
// let 3 = 2; // naming variable can only start with letter/$/_
let result = 3 + 4;
// 3. Variable names cannot be reserved keywords
// let let = 12;

View File

@ -0,0 +1,26 @@
// Multiple arguments
let add = function (a, b, c) {
return a + b + c
}
let result = add(10,1,5)
console.log(result)
// Default arguments
let getScoreText = function (name = 'Anonymous', score = 0) {
console.log(name)
console.log(score)
}
getScoreText()
// Challenge area (tip calculator)
// Argument: total, tipPercent (default = 20%)
// Output: return tip value
let calcuateTip = function (total, tipPercent = .2) {
return total * tipPercent;
}
console.log(calcuateTip(100,.4));
let name = 'Jen';
console.log(`Hey my name is ${name}`)

View File

@ -0,0 +1,25 @@
// Function - input (aka argument), code, output (aka return value)
let greetUser = function () {
console.log('Welcome user!');
}
greetUser();
let square = function (input) {
return input*input;
}
console.log(square(3));
// Challenge Area
// Convert FahrenheitToCelsius
let convertFahrenheitToCelsius = function (num) {
let celsius = (num - 32) * (5/9);
return celsius;
}
// Call a couple of times (32 -> 0) (68 -> 20)
console.log(convertFahrenheitToCelsius(32));
console.log(convertFahrenheitToCelsius(68));
// Print the conveted values

View File

@ -0,0 +1,17 @@
// Global Scope (convertFahrenheitToCelsius, tempOne, tempTwo)
// Local Scope (fahrenheit, celsius)
// Local Scope (is Freezing)
// Convert FahrenheitToCelsius
let convertFahrenheitToCelsius = function (fahrenheit) {
let celsius = (fahrenheit - 32) * (5/9);
if (celsius <= 0) {
let isFreezing = true
}
return celsius;
}
// Call a couple of times (32 -> 0) (68 -> 20)
console.log(convertFahrenheitToCelsius(32));
console.log(convertFahrenheitToCelsius(68));
// Print the conveted values

View File

@ -0,0 +1,24 @@
// Arg: students score, total possible Mark
// 15/20 -> You got a C (75%)
// A: 90-100, B 80-89, C 70-79, D 60-69, F 0-59
let calcGrade = function (score, totalScore) {
let percent = score / totalScore * 100;
let letterGrade = '';
if (percent >= 90) {
letterGrade = 'A';
} else if (percent >= 80 && percent <= 89) {
letterGrade = 'B';
} else if (percent >= 70 && percent <= 79) {
letterGrade = 'C';
} else if (percent >= 60 && percent <= 69) {
letterGrade = 'D';
} else {
letterGrade = 'F';
}
return `You got a ${letterGrade} (${percent}%)`
}
let result = calcGrade(15, 20)
console.log(result);

View File

@ -0,0 +1,6 @@
let name;
console.log(num);
name = null;
console.log(name);

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html>
<head>
This is big header
</head>
<body>
<h1>Notes App</h1>
<h2>Take note here and never forget</h2>
<p>This application was created by Jason Zhu</p>
<p>Some notes text</p>
<script src="notes-app.js"></script>
</body>
</html>

View File

@ -0,0 +1,19 @@
// DOM - Document Object Model
// const p = document.querySelector('p')
// p.remove()
// Query all and do some operations
const ps = document.querySelectorAll('p')
// Remove
// ps.forEach(function (p) {
// p.remove()
// })
// Read/Write HTML document elements
ps.forEach(function (p) {
// console.log(p.textContent)
p.textContent = '****'
})

View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Todos</h1>
<p>Clean the kitchen</p>
<p>Book flights</p>
<p>Research museums</p>
<p>Walk the dog</p>
<p>Finish this course!</p>
<script src="todo-app.js"></script>
</body>
</html>

View File

@ -0,0 +1,9 @@
Part 1:
1. Create a new HTML file
2. Add an h1 and 5 p tags
3. Server that folder and view the doc in the browser
Part 2:
1. Create an link a JS file to HTML
2. Iterate all todo paragraph and remove p tag that have "the"

View File

@ -0,0 +1,46 @@
const todos = [{
text: 'Order cat food',
completed: false
}, {
text: 'Clean kitchen',
completed: true
}, {
text: 'Buy food',
completed: true
}, {
text: 'Do work',
completed: false
}, {
text: 'Exercise',
completed: true
}]
const ps = document.querySelectorAll('p')
ps.forEach(function (p) {
if (p.textContent.includes("the")) {
p.remove();
}
})
// Add a new element
const newParagraph = document.createElement('p')
newParagraph.textContent = 'This is a new element from JavaScript'
document.querySelector('body').appendChild(newParagraph)
// You have 2 todos left
// Add a p for each todo above
const incompleteTodos = todos.filter(function (todo) {
return !todo.completed;
})
const summary = document.createElement('h2');
summary.textContent = `You have ${incompleteTodos.length} todos left`; // Template literals (template string)
document.querySelector('body').appendChild(summary);
todos.forEach(function (todo) {
const p = document.createElement('p');
p.textContent = todo.text;
document.querySelector('body').appendChild(p)
})