Variables
var vs let (function vs block scope)
if (true) { var x = 0; let y = 1; } console.log(x); console.log(y);
undefined value
console.log(z); var z = 2;
automatic global variables
function f() { v = 1; } f(); console.log(v);
prevent automatic globals with “use strict”
Objects
JavaScript objects are associative arrays
o = {a: 1, 1: 'a'};
can use dot notation or array notation
console.log(o.a); console.log(o['a']);
Arrays
array literal
a = [1, 2, 3]
array constructor (can be confusing, one argument vs many do different things)
a = Array(1) b = Array(1, 2)
Functions
functions are values
var f = function() { console.log('f'); }
also a more c-like declaration
function f() { console.log('f'); }
parameters can be undefined
function f(x) { console.log(x); } f();
closures
function f(x) { var g = function() { console.log(x); } return g; } var h = f(1); h();
arrow functions
var a = [1, 2, 3]; var a2 = a.map(function(i) { return i * 2; }); var a3 = a.map(i => i * 2);
Classes
classes are objects with function attributes
var obj = new Object(); obj.thingie = 1; obj.do = function() { console.log('do'); };
define a constructor as a function
function Object(thingie) { this.thingie = thingie; obj.do = function() { console.log(this.thingie); } } var obj = new Object(1); obj.do();
If
c-like
if (x < 2) { console.log(x); }
== vs ===
let x = 2; if (x == '2') { console.log('equal'); } if (x === '2') { console.log('equal'); }
Loops
for, for in, for of
for (let i = 0; i < 3; i++) { console.log(i); } for (i in array) { console.log(i); } for (o of obj) { console.log(i); }
while
var i = 0; while (i < 3) { console.log(i); i++; } i = 0; do { console.log(i); i++; } while (i < 3);
AJAX HTTP Request
In javascript, use AJAX to get the json string
var handleResponse = function() { if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) { console.log(httpRequest.responseText); } } var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = handleResponse; httpRequest.open('GET', 'http://cs.roanoke.edu/~username/sql.php', true); httpRequest.send();
Parse JSON
In the response handler, convert the json string to a JavaScript object
var responseList = JSON.parse(httpRequest.responseText); for (var i = 0; i < responseList.length; i++) { console.log(responseList[i]); }
Update HTML
Use the Javascript object to update the HTML document
var responseList = JSON.parse(httpRequest.responseText); var orderedList = document.getElementById('theList'); for (var i = 0; i < responseList.length; i++) { var item = document.createElement('li'); var text = document.createTextNode(responseList[i]); item.appendChild(text); orderedList.appendChild(item); }