JavaScript

  • Netscape dude created JavaScript in 1996 in 10 days
  • mix of ideas from C, Self, & Scheme
  • AKA ECMAScript
  • in the browser with access to the DOM (webpage - document object model)
  • it's interpreted (like python, perl, or ruby) - means not compiled: there's a program that runs your program.
  • object-oriented, with prototypes
  • loosely typed (aka untyped)
  • lexically scoped
  • lambda-oriented (first class functions)

Implemented in your web broswer

  • to start the browser's interpreter, put into an HTML file: And then in 'test.js': document.write("Hello World!");
  • browsers compete for fastest JS interpreter

OUTPUT 4 ways to output:

  • 1) directly to HTML: document.write("hello")
  • 2) pop up (window.alert("hello");. DON'T DO THIS
  • 3) browser's debug console (do this!! in chrome it's view/developer/developer tools): console.log("hello")
  • 4) modify existing HTML (useful for making interactive web pages):

DATA TYPES: numbers: everything is a float! var pi = 16; strings (no char): + concats strs

- "Hello World".length === 11;
- "Hello World".toUpperCase();

Arrays: var chickens = ["A", "B"]; Objects: var x = {first:"Robin", last:"Mehta"};

  • types change at runtime
  • AKA untyped AKA loosely typed
  • var x = 10; x = "Hello World" is OK!!!

  • simple functions: function add(a, b) { // if a,b types are not compatible, it would convert the type to a string, and concatenate that string return a+b; }

  • call it: var total = add(1,10)
  • document.write(total);

  • variables are call-by-object

  • primitives are passed by value
  • objects are passed by reference
  • references themselves are passed by value (if you overwrite the actual object (creating a new object & overwriting the address), then it won't affect the original object. that would just be a copy)
  • garbage collector searches for variables who no longer have references to them
  • == does type coercion, === does not
  • functions create scopes, blocks DO NOT (so you can use variables outside an if statement, even if you declared it inside the if statement)

GLOBAL VARS (don't put "var" and it makes it global)

  • var x = 10
  • y = 5 (global)

  • NO LINKER. anything you import is global namespace

  • first class functions: functions can be created, destroyed, passed as inputs, & returned as outputs AT RUNTIME.

  • functions as variables var add = function(a, b) { return a+b; }

call it: var total = add(1,10)

uses of functions: 1) standalone 2) as a method of an object (when the var is created, the function is created) 3) apply-style: var numList = [1, 2, 3, 4]; var total = add.apply(null, numList); // total === 10; 4) constructor-style (invoked w/new): var list = function(v, n) { this.v = v; this.n = n; } var1 = new List(1, 2);

  • prototypes: class free inheritance
  • you can add vars at runtime
  • more like a dictionary than anything