var userName = "Jack"; // Globally
let userName = "Jill" // Narrow scope: for loop
const interestRate = 4.25 // Final and Global, cannot change
var firstName = "Ru", lastName = "Wang", age = 26; // different data type same line
typeof firstName-->"string"
// Object: unorderd collections of data of PRIMITIVE/REFERENCE types->key: value statements
var TA = {
firstName: "ALice",
lastName: "Smith",
age: 24
}
TA.lastName-->"Smith"
TA["lastName"]-->"Smith"
// Array: can contain elements of different types
var students = ["Andy", "David","Laura"];
students[3] = "Nathan"; // QUESTION HERE
students[4] = 4
// Function: Easy for debugging, recursion
function nameFunc(parameters){
// Calculate
}
// Anonymous Function: Easy for scope, brevity
var first = function(array){return array[0]};
var first = array => return array[0]; // arrow function
// Function serve as methods with objects
var Report = {
temp: 77,
humidity: 64,
celcius: function(){ // Anonymous funciton, no Name
reuturn (this.temp-32)*5/9;
}
}
// Conditionals
if...else
switch
Ternary operator
=== & !== (identical to/not identical to objects, value & type)
== & != (values, not type)
// Any value that is not false, undefined, null, 0, NaN, "" return true
var current = "Alice";
if(current){ // evaluate to true
...
}
// Ternary
(condition)? doSth: doSthElse
// for loop
for(initializer; exit-condition; final-expression){
...
}
document.getElementById("convert").onclick = "convertTemp"; // No ()
function convertTemp(){
...
}
// Event Listeners
document.getElementById("convert").addEventListener("click", convertTemp); // No ()
function convertTemp(){
...
}
// Change multiple elements, all buttons have the same event in this case
document.body.addEventListener("click", event=>{
if(event.target.nodeName=="BUTTON"){
console.log("Clicked", event.target.textContent);
}
});
// JSON Objects
{
"firstName": "dd",
"role": "Instructor"
}
// JSON Arrays
{"TAs": [
{"Name": "1", "Year": 2022},
{"Name": "1", "Year": 2022},
{"Name": "1", "Year": 2022}
]
}
// Use JSON
var text = JSON ARRAY;
obj = JSON.parse(text);
obj.TAs[0].Name, obj.TAs[1].Year
// Request JSON from server
Synchronous OR Asynchronous(Recommanded, produce a callback when data received)
// Callback Function
function greeting(name){ // Synchronous Example
alert("Hello", name);
}
function processUserInput(callback){
var name = prompt("Enter your name");
callback(name);
}
processUserInput(greeting);
XMLHttpRequest() & fetch(): Promise-based method, new
Promise objects represents the eventual completion/failure of an
async operation and its result value;
// XMLHttpRequest()
var url = "tas.json";
var req = new XMLHttpRequest();
req.open('GET', url, true); // true for async
req.responseType = 'json';
req.onload = function(){
...
}
req.send();
// fetch
fetch(url)
.then(response=>response.json())
.then(data=>{
...
})
.catch(error=>console.error(error));
// parse and stringify
var tas = parse(JSON); //JSON->JS
var tas = stringify(JS); //JS->JSON