The code that we ran above:
// variable scope with and without var:
var n = 2;
m = 5;
function f() {
document.write("n = " + n + "<br />");
document.write("m = " + m + "<br />");
var n = 3;
m = 6;
document.write("n = " + n + "<br />");
document.write("m = " + m + "<br />");
}
f();
document.write("n = " + n + "<br />");
document.write("m = " + m + "<br />");
// functions are first-class
function g1(n) {
return n + 1;
}
document.write("g1 is a function: " + g1 + "<br />");
document.write("g1(2) = " + g1(2) + "<br />");
g2 = function(n) {
return n + 1;
}
document.write("g2 is a function: " + g2 + "<br />");
document.write("g2(2) = " + g2(2) + "<br />");
// higher-order functions:
function h(g, n) {
return g(g(n));
}
document.write("h(g1, 3) = " + h(g1,3) + "<br />");
document.write("h.name = " + h.name + "<br />");
// the number of arguments
document.write("h.length = " + h.length + "<br />");
// Javascript objects:
var person = {firstName:"Mary", lastName:"Smith", DOB:1997, eyeColor:"blue"};
document.write("name = " + person.firstName + " " + person.lastName + "<br />");
document.write("name = " + person['firstName'] + " " + person['lastName'] + "<br />");
person.location = "Morris";
document.write("name = " + person.firstName + " lives in " + person.location + "<br />");
person.moveTo = function(newPlace) {this.location = newPlace};
person.moveTo("New York");
document.write("name = " + person.firstName + " lives in " + person.location + "<br />");