Lab 04: Javascript Basics

Another week, another language! This is in some ways a ridiculous way to learn about programming, and you may not remember all you learn. The most important thing is to get some sense of the types of operations that take place when programming languages interact with web pages, so you can change the code you are given to get it to do exactly what you want. But in order to do this it wil lbe very helpful to know just a little bit about programming in general.

What is Javascript and why do we learn it?

You’ll remember that I made a a very general division early in the semester:

Structure Style Dynamic Content & Effects
HTML CSS Javascript

In contemporary web pages, a lot of the work that runs the page is done by javascript. This is easy to see, e.g., in the “Network” or “profiler” tabs of the developer tools in Chrome or Firefox. In general, if you want to make changes to a web page after it’s written, javascript is the easiest way to do it (except for CSS animations, I guess).

Javascript also has uses outside the browser – the Atom editor is written in Javascript, for instance.

Running Javascript

Because we use javascript mostly to manipulate web pages, it can be a little hard to run javascript programs. Here are a couple of ways to try javascript form inside your browser:

Run in Atom Editor

This might be the easiest (though eventually you will need to run in a browser, e.g., if you want to practice manipulating DOM elements). Install the script-runner package, or one off the alternatives like run in atom or script, and follow directions to run code directly in the editor.

Console

Both Chrome and Firefox have built-in “Javascript Consoles” accessible from the developer tools: Tools \rarr Web Developer \rarr Console or Menu \rarr More Tools \rarr Developer \rarr Console

Scratchpad

The FF console is a little awkward to use for multi-line programming, so they have also provided a “Scratchpad” tool (Shift-F4), which I find helpful.

Accessing the console

When you run code in the browser, the easiest way to print something is with the console.log function. This prints text to the console so you will have to open the console to see if your code is working.

some code to paste into your console or scratchpad

We can start by just fooling around with a little test code.

/*
 Here are some basic javascript constructs you will encounter in your homework
 */

// two ways to "print"
console.log("hello");
// alert("hello");


// here is a very basic "for loop":
for (i=0; i<10; i++ ) {
  console.log("this is number: " + (i+1));
}

// a simple array -- essentially a list
var veggies = ["carrot", "potato", "pea"];

// a "for-of loop" -- iterates over array items
for (i of veggies) {
  console.log(i)
};

// a for-in loop -- iterates over array length (0,1,2,3, etc)
for (i in veggies) {
     console.log(veggies[i])
     };


// the same stuff, now applied to a web page
// this stuff won't work from inside your editor!
// try with other element types: h2, p, etc.  
var headings = document.getElementsByTagName("h1");
console.log(headings);
for (i=0; i<headings.length; i++) {
    headings[i].innerHTML = i + 1 +". " + headings[i].innerHTML;
    console.log(headings[i].innerHTML);
};

// this will overwrite the whole document!
//document.write("hello");

// objects

// defines a new object type: Animal
function Animal (name,numLegs) {
    this.name=name;
    this.numLegs=numLegs;
}


// creates a variable of type Animal
var penguin = new Animal("Penguin", 2);

// shows the internal structure of the object
console.log (penguin);

// you can iterate over the penguin's attributes
for (i in penguin) {
    console.log(i + ": " + penguin[i]);
}

// Add a new "method" to the object
Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};

Variables

You have all taken algebra, so you have all seen variables. Let’s think of it this way: a variable is a box, into whic you can place a value.

var myString = "Hello, everyone";
console.log(myString);
var myString = "some value in here";
var myNumber = 47;
var myArray = ["first is a string", 2, "third is also a string"];
var myObject = {first:"first is a string", second: 2, third:"third is also a string"};

In almost all programming languages, there are many variable “types”; javascript variables are “dynamically typed”, which means that the type is determined only when the variable is actually being used. This is very handy, but can sometimes lead to confusion, e.g., compare:

console.log("Hello, I am a string " + 1 + 2);
console.log(1 + 2 + " but I am a number");

Iteration and Control Structures

Every computer language has “control structures”

Loops

// here is a very basic "for loop":
 for (i=0; i<10; i++ ) {
   console.log("this is number: " + (i+1));
 }

 // a simple array -- essentially a list
 var veggies = ["carrot", "potato", "pea"];

 // a "for-of loop" -- iterates over array items
 for (i of veggies) {
   console.log(i)
 };

 // a for-in loop -- iterates over array length (0,1,2,3, etc)
 for (i in veggies) {
      console.log(veggies[i])
      };
for(var i = 0; i < 10; i++) {
    console.log("This is iteration number: " + (i + 1) );
}

Flow Control

also if statements – what will this print?

var dimensions = 3;

if (dimensions > 3) {
    warp.speed("Make it so");
} else {
    console.log (" I dannae think she can take any more, Captain!");
}

You’ll learn a few more in the homework (notably switch/case and try/catch); but these two do the two basic operations you need to understand: repeat and test.

Accessing the DOM

Javascript uses something called the Document Object Model to understand the web page. As far as Javascript is concerned, the DOM is a big complex object, whose parts can be identified, manipulated, and used as input for complex functions. Here’s a relatively simple operation you can try in the Firefox scratchpad with a :

var headings = document.getElementsByTagName("h1");
console.log(headings);
for (i=0; i<headings.length; i++) {console.log(headings[i].innerHTML);};
// alert(headings);

Objects

Objects deserve special mention, because they can be hideously complex.

// defines a new object type: Animal
function Animal (name,numLegs) {
    this.name=name;
    this.numLegs=numLegs;
}


// creates a variable of type Animal
var penguin = new Animal("Penguin", 2);

// shows the internal structure of the object
console.log (penguin);

// you can iterate over the penguin's attributes
for (i in penguin) {
    console.log(i + ": " + penguin[i]);
}

// Add a new "method" to the object
Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};

Functions

Functions in JS are defined in two ways:

As a declaration:

function square(number) {
  return number * number;
}

As an expression:

var square = function(number) { 
    return number * number 
};

Functions in Javascript are “first-order objects” and can be used in mind-bending ways. You don’t need to worry about those for a little while yet.