A Little introduction to JavaScript

JavaScript is the programing language used in Field. It’s also the programing language built into every modern web-browser and, by expectation, every modern web-page. It’s designed to be fairly simple to learn, but sometimes that ‘simplicity’, and the sediment that years of “improvement” have left behind, can make it harder to pick up. It’s also sometimes hard to differentiate between JavaScript “the language” and JavaScript “doing things in web-browsers”. This page collects the basic facts that you might need to feel comfortable moving forward in the language before you head off to one of the many online tutorials. It’s best experienced interactively — open Field and start typing.

Variables

Here’s a line of JavaScript:

var hello = "Hello World"

First let’s note the colors. Despite my muted color scheme you might see that var, hello, = and "Hello World" are all in different colors. Field is trying to tell you something — these words have different grammatical roles.

  1. var is a keyword — a special word with special meaning. Talking about var and what it does is talking about the language itself.
  2. = is also a special kind of word. Here it sets the thing on the left to have the value of the thing on the right. It’s a verb, it does something.
  3. hello is our word. Within the rules of JavaScript it could be anything. As long as we are consistent it has the meaning that we give it.
  4. "Hello World" is a String — that is a piece of text. That really can by anything. It’s bracketed by " characters. That’s how you write a string (it makes it easy for the computer to figure out what’s a string and whats actually code.)

What does this code do? It introduces (var) a new variable called hello and puts into it the String Hello World. A variable here is just a named box with something in it. The name is hello and the something is the String Hello World.

If you execute that line of code (option-return with the cursor on the line), then Field will briefly show a checkmark to let you know that everything has gone OK.

If you then execute just hello, you’ll see the ‘contents’ of this variable:

Field is decorating your code there with red ink — if we didn’t just execute that line by itself it would do anything — it would simply name a variable and move on. Writing code that doesn’t do anything smells fishy, so Field warns you. We could try:

and everybody is happy.

Other kinds of variables

JavaScript has a compact set of things that things can be (often called types) and ways of ‘spelling them’:

var myGreatString = "greatness"
var aNumber = 1.5
var aList = [5,4, 3.2, "hello", myGreatString]
var anObject = {hello:"there", a: 2.3}

As before the names of these variables are arbitrary (within rules: I couldn’t call them var for example, that would be weird. Nor could I call them = or +, or {}).

The first two are straightforward — text and numbers. Then there is a list spelled by putting things in between square brackets [], separated by commas (just like English). Lists in JavaScript can be lists of anything (including lists, and other variables).

Objects are the most complex thing we’ll encounter: they are groups of named things. Again, objects can contain other objects (and lists and numbers etc). Inside our anObject above hello has the ‘value’ "there" and a has the value 2.3.

Doing things with lists

Now that we know how to spell a list, we can do things with and to them.

var aList = [5,4, 3.2, "hello"]
print(aList[0])

aList[0] gets the ‘zero-th’ element of the list. 0?? Let’s agree to call this the first element. Lists are indexed in JavaScript starting at 0 not 1. Believe it or not this makes some things easier (but harder to talk about). aList[1] would be the second element.

We can also write:

var aList = [5,4, 3.2, "hello"]
aList[0] = 20

That will change the first entry of aList to be 20. Note we don’t need the var here (in fact we’re not allowed to have the var here) — we are not introducing a new variable.

Doing things with objects

var anObject = {hello:"there", a: 2.3}
print(anObject.hello)

Yields:

To get things out of objects we can use the . notation. We can also use [] as well: print(anObject["hello"]) works just the same. Note we need the " marks around the hello` in this case.

We can change objects contents just the same:

var anObject = {hello:"there", a: 2.3}
anObject.hello = 14.53

Now if we print(anObject.hello) we’ll get 14.53

Doing things to lists

Here’s a secret: lists are just a kind of Object. While we might put three things in them, there are other things hiding in there already:

var aList = [5,4, 3.2, "hello"]

aList.push("world")

print(aList)

What’s going on with aList.push("world"). Clearly running that has added "world" to the end of our list. Let’s break it down:

  1. aList.push is a function
  2. ("world") runs that function, with the parameter "world".

If we just run aList.push everything is fine, but nothing is done (we’ll get some red ink from Field for our troubles).

You’ll recall functions from grade-school — f(x) = mx+c and all that. Here the act of writing those circular brackets ‘()’ potentially with things in between them does that function. Here its a function called push that we can find in any list. That there’s a thing called push inside lists is part of any JavaScript.

You’ll also find, on lists, ‘.length` to be useful:

Our own functions

We can define our own functions:

var myFunction = () => {
    return "hello world"
}

Part of this we’ve seen before: var is doing the same thing, myFunction is an arbitrary name, = is setting the thing on the left to be the thing on the right. What’s new is the thing on the right:

() => {
    return "hello world"
}

That ‘spells’ a function that, when invoked returns the value “hello world”.

So, for example:

We could also write:

Now we have a function that takes one parameter and uses it. For the purposes of the function that parameter will be called ‘x’. Outside the function x doesn’t exist (or if it does — if it has been var-ed into existence — it’s a completely separate thing). The parameter list is in () brackets, the ‘body’ of the function – what it does – is in {} brackets.

We should note, in both cases, that if we merely define a function, or write one out, we’re not actually doing it. Until we add () to the end of its name, we’re merely naming it or telling the computer what we want it to be.

Making special objects

Sometimes in Field you need to make an object that comes with special functionality — not just the default things you might find in any list or object. One good example of this is an FLine. You make special objects with the new keyword:

var f = new FLine()
f.moveTo(10,20)

Any FLine comes with all kinds of things built into it (here: a moveTo function). Most special functions are part of Field, (or the web-browser) not JavaScript per se. The very special box variable in Field called _ has already been newed for you.

Control flow

So far we’ve been able to figure out how our code is going to run by moving from top to bottom (and we carefully remember the difference between defining or naming functions and actually running them). JavaScript has a few structures for interrupting this orderly progression from top to bottom.

The for loop

Here’s a looping structure called a for loop. It’s a nasty looking nest of punctuation, but it’s the best we got:

for(var i=0;i<5;i=i+1)
{
    print(i)
}

That for loop does something 5 times, and each time around it adds one to a variable i, counting from 0 to 4 (inclusive)

The for loop has four parts:

for( AT-THE-START ; KEEP-GOING-WHILE ; DO-AT-THE-END-OF-THE-LOOP )
{
    THING-TO-DO
}

so, for each part with our example:

  1. AT-THE-START, do var i=0, make a variable called i with the value 0 in it.
  2. KEEP-GOING-WHILE, while i<5 keep doing this loop, otherwise, stop doing the loop.
  3. THING-TO-DO, is the thing done.
  4. DO-AT-THE-END-OF-THE-LOOP, after THING-TO-DO is done, we add one to the value of i. This is almost always written in shorthand i++. This is put up at the top, even though it happens ‘at the bottom’ because if you miss it out, your loop will likely go on forever. This is bad.

The if statement

This one is comparatively simple:

var i=2
if (i<5)
{
    print("i is less than 5)
}
else
{
    print("i is not less than 5)
}

The else block is optional.

In pseudo-code again:

if (CONDITION)
{
    THING-TO-DO-IF-CONDITION-IS-TRUE
}
else
{
    THING-TO-DO-OTHERWISE
}

Errors

Inevitably, things will go wrong. Field tries hard (really hard) to give better errors than average; but sometimes confusion of the computer leads to confusion as to what the confusion is about.

Things that you’ll see:

That’s a typo in hello — which becomes a ReferenceError “hell0” is not defined.

With objects, things can get a little more cryptic:

Since hello.s0omething isn’t, well, anything, asking for a from nothing (aka undefined) is the error.

Same thing when calling a function that doesn’t exist (or is, otherwise, not a function at all):

For the record, hello.something() gives the same error — hello.something is an object, not a function.

The slop

Finally, perhaps the hardest thing about learning JavaScript by Googling everything, is that the language has evolved quite a bit (and continues to do so). It also didn’t start off in a particularly great place (the first version was written in 10 days in 1995, and here we are…).

You’ll see a few different ways of doing (essentially, but not quite the same) thing.

For functions:

var f = (x) => {
    return x*5
}

var f = (x) => x*5

var f = function(x) {
    return x*5
}

function f(x) {
    return x*5
}

For blocks you can skip the {} if you only want one line

if (i<5)
    print("hello")

if (i<5)
{
    print("hello")
}

There’s also the unfortunate ambiguities concerning semi-colons at the end of statement (which should be there, but are so well infered when they are absent that it’s hard to remember to put them in).

Additionally some pages will teach you let over var or even const (which is a var that can only be defined once, which is less useful when live-coding). By the time you know enough care about the not particularly important differences between these syntaxes you, well, won’t have trouble with them.