Intro to 

JavaScript

(Part One)

Why JavaScript?


When I was preparing this course, I decided that it would be good to have a real practical element, and that we should
"get our hands dirty" and do some programming...

...but I didn't want to get them too dirty!

But why JavaScript ?!?!1one!


I wanted to avoid the need for a complicated IDE and an awkward edit/compile/link/debug workflow.  I didn't want there to be complex installation requirements for the development tools, and I didn't want to be tied to any particular OS.

I also thought it would be nice if the fruits of our labours could be easily shared with others, which made portability and ease of "installation" a big factor.

=> JavaScript in a web browser.  

But!


"JavaScript is slow..."
"...and ugly"
"...and broken"
"...and is a toy language for amateurs"

:-(

What is JavaScript?


Arguably, it is (or was):

The World's 
Most Misunderstood Programming Language
http://crockford.com/javascript/javascript.html




The Language of the Browser


Pragmatically, the important thing about JS is that it's the scripting language of the web-browser.

Without it, web-pages would look like flat slabs of text,
just as they did back in 1993.

The WWW!

(Some extra context and background can be found here).

The Wayback Machine


Early Google

For a modern-day equivalent of a script-free bare-bones Web from the past, just go to the homepage of almost any university academic.

Today


In contrast, when you see lots of magic shiny interactive stuff jumping out at you on a modern webpage, you're most probably looking at the effects of JavaScript.


This slideshow!

How?


When JavaScript is running inside a webpage, it's typically manipulating the otherwise static structure of the page.

That structure is made available to the JavaScript code
by the browser, via an interface called the DOM
(Document Object Model)

In conjunction with CSS (Cascading Style Sheets) to handle styling info, this allows us to augment and beautify the plain old HTML (HyperText Markup Language) of the web.

Games?


More recently, the introduction of the "canvas" element in HTML5 also lets us have almost direct control over exactly what is displayed in specific regions of a webpage,
and that's what is starting to make it a viable
(and interesting) target for games.

The Good News


You already know parts of JavaScript...
...sort of

The prerequisites for this course are introductory-level 
Java and C++.

Those languages share a very similar "braces and semi-colons" syntax, and that's what JavaScript uses too.

They both support "object oriented" programming,
and so does JavaScript.

Is it like Java?


Not as much as you might think from the name.

However, there are similarities:

Variables are considered to be "references" to some other piece of data (rather than C-style "values" of their own). This means that assignment to a variable actually involves the copying of references, not the copying of "objects".

Also, JavaScript is a garbage-collected language in which you aren't responsible for explicitly managing memory.

Some Examples


What it looks like:
function linkify( selector ) {
  if( supports3DTransforms ) {

    var nodes = document.querySelectorAll( selector );

    for( var i = 0, len = nodes.length; i < len; i++ ) {
      var node = nodes[i];

      if( !node.className ) {
        node.className += ' roll';
      }
    }
  }
}
'for', 'if' (and 'while'), behave just like the C++ / Java forms.
conditionals are similar too e.g. && for AND, || for OR, ! for NOT

Let's Write Some Code!

Use the browser's developer console to try stuff out...

(CTRL-SHIFT-I for devtools on Windows, CMD-ALT-I on Mac)

NB: The console doesn't have a "strict mode",
so it lets you create vars without declaring them.
This turns out to be convenient for small examples
(but is dangerous for larger ones).

I also take advantage of JavaScript's "semicolon insertion"
(mis-)feature in the console, but try not to in "real" code.

Hello Console


> "hello"
"hello"
> "hello" + " " + "world"
"hello world"

Is this more fun than Java?
public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("hello world");
  }
}

Yes.

Arithmetic


> 1234
1234
> 2 + 2
4
> 3 * 4
12
> 12 / 4
3
> 12 / 5
2.4
> 10 / 3
3.3333333333333335
> 0.1 + 0.2
0.30000000000000004

It's not a bug, it's a feature!
(Here's a decimal to double converter)

Do the Math(s)!


> 17 % 5                   // '%' means "modulus" i.e. remainder
2
> 17.1 % 4.9               // ..slightly weird with non-integers!
2.4000000000000004
> Math.PI                  // approximately, of course!
3.141592653589793
> Math.pow(2, 8)
256
> Math.pow(8, 2)
64
> Math.sin(0)
0
> Math.sin(90)             // it's not in Degrees...
0.8939966636005579
> Math.sin(Math.PI / 2)    // it's in Radians
1

Variables


> hello
ReferenceError: hello is not defined
> var hello       // NB: `var` is a statement; it produces no value
undefined
> hello           // The var `hello` now exists, with a default value
undefined
> hello = "Greetings!"  // Assignment gives it a new value
"Greetings!"
> hello                 // Which we can now display
"Greetings!"
> greet = hello         // Didn't declare this; implicit `var` 
"Greetings!"
> var greet = hello     // Explicit `var` in the console is annoying
undefined
> greet === hello
true

Types


> hello = "hi"
"hi"
> greet
"Greetings!"
> greet === hello      // "===" for sensible equality-testing
false
> greet !== hello      // "!==" for sensible not-equality-testing
true
> hello = 99           // A dynamic change of type!
99
> typeof hello
"number"
> typeof greet
"string"
> typeof typeof hello  // because "typeof hello" returns a string
"string"

Functions


> square = function (x) {return x * x;}
function (x) {return x * x;}
> square
function square(x) {return x * x;}
> typeof square
"function"
> square(3)
9
> square(4)
16
> square()      // unspecified params have the special val: undefined
NaN             // arithmetic on undefined gives "Not A Number" (NaN)
> square(5,6,7,8)                         // extra params are ignored
25
> timesSelf = square   // you can assign functions, like other values
function (x) {return x * x;}

Mystery


> mystery = function (a, b) {a + b;}
function (a, b) {a + b;}
> mystery(1, 2)      // Oops! Forgot "return"; defaults to undefined
undefined
> mystery = function (a, b) {return a + b;}
function (a, b) {return a + b;}
> mystery(1, 2)      // Now it should work.
3
> mystery = function (a, b) { // SHIFT-ENTER to cont. on a new line
    return a + b;
  }
function (a, b) { // SHIFT-ENTER to cont. on a new line
  return a + b;
}
The use of SHIFT-ENTER for multiline input is occasionally useful
but, typically, the console is just for one-liners.

Function Statements


> sq1 = function (x) {return x * x;}  // NB: A function *expression*
function (x) {return x * x;}
> function sq2(x) {return x * x;}     // NB: A function *statement*
undefined
> sq2
function sq2(x) {return x * x;}
> sq2.name
"sq2"
> sq1.name
"sq1"                                 // NB: In the past, "" (!)
> sq3 = function name(x) {return x * x;}
function name(x) {return x * x;}
> sq3.name
"name"
> var sq4 = function sq4(x) {return x * x;}  // rough equiv of sq2
undefined

Arrays


> a = []
[]
> a.length
0
> a = ["apple", "banana", "cherry"]
["apple", "banana", "cherry"]
> a.length
3
> a[0]
"apple"
> a[1]
"banana"
> a[2]
"cherry"
> a[3]
undefined

More Arrays


> a[1] = 99
99
> a
["apple", 99, "cherry"]
> a === ["apple", 99, "cherry"]  // surprising!
false
> a === a
true
> a[5] = "pear"
"pear"
> a
["apple", 99, "cherry", undefined × 2, "pear"]
> a.length
6
> typeof a
"object"

Strings


> "hello"[1]
e
> s = "World"
"World"
> s[3]
"l"
> s[3] = "e"
"e"
> s  // NB: strings are array-like (and have 'length'), but are immutable!
"World"
> "hello" + " every" + 1
"hello every 1"
> 1 + 2 + "3" + 4 + 5 + "6"  // adding with a string "stringifies" 
"33456"
> 1 + 2 + "3" + 4 + 5 - "6"  // subtracting with a string... oh my god
3339

The Joy of Fiddling



This gives you a nice little online IDE for
creating and sharing small JavaScript snippets
(i.e. those which fit within a single source file).

An example to get you started (up to version /3):

(Just be careful to copy/save often. If you create an infinite loop you might struggle to recover any unsaved code.)

Level 1 Neural Implant Complete



You know JS-Fu!

Homework


You should now know enough to complete the homework assignment for this week!

It requires you to use jsFiddle to solve a series of increasingly difficult programming problems, requiring the manipulation of numbers, strings and arrays...


Save your new fiddle, and then fill in your answers.
(Use "Update" to save subsequent changes).

But that would be too easy!


So I want you to do it with no help from the built-in functions, or any kind of "standard library".

i.e. with one hand tied behind your back.

...just to make it interesting ;-)

This can be done with what you know.

Good Luck!

IMPORTANT


Read the homework instructions carefully.

There are some subtleties here.

In particular, you must use the specified function names.

...and don't try to be clever by using "for ... in" loops
(they won't work, and you will lose marks for it).

Intro to JavaScript (Part One)

By Pat Kerr

Intro to JavaScript (Part One)

A high-level overview, which assumes prior familiarity with C++ and Java.

  • 2,131