Yep, that's my face

Troy Lamerton

Javascript Basics

7 April 2016

A website without javascript is like a house without electricity. You can walk around the house and it looks nice, but you can't turn any gadgets on, and after a while you'd rather be somewhere else.

Javascript is the most like a traditional programming language when compared to HTML and CSS. HTML is the foundational structure and CSS is the aesthetics. Javascript powers the interactive parts of websites. When you open your notifications on Facebook or expand a tweet on Twitter, it's most likely Javascript that's at work.

The uniqueness of Javascript (compared to HTML and CSS) is how it can make decisions about what to do. This is like waking up in the morning. Depending on a few conditions will affect what you do. Am I working this morning? Do I have nothing on? Am I still tired from last night? If I [have work] I'll [get up], otherwise I will not [get up] and if I am also [tired from last night] I will [sleep in].

In Javascript this looks like:

var haveWork = false;
var tiredStill = true;

wakeUp = function () {
  if (haveWork) {
    getUp();
  }
  else {
    if (tiredStill) {
      sleepIn();
    }
  }
}

How about doing something repetitive though?
Could something like painting a picketed fence be explained in Javascript? Sure can! First we need to know how to paint one picket. We will paint one picket and then another and so on. But we also need to know when to stop painting pickets or we'll have angry neighbours to deal with. We need to stop when there are no more pickets to paint. While there are more pickets to paint, paint another picket.

In Javascript this looks like:

while (picketsLeft >= 1) {

  //Paint the picket upwards
  //Paint a stroke downwards
  //Fill in the gaps
  
  picketsLeft--;
};

Objects and arrays... Objects store variables which are assigned values. For example, a Car object might have the variables MaxSpeed = 200, Wheels = 4, Colour = "red". An array is a special type of object. While standard objects can name their variables, arrays are an ordered list of values. The way to identify items in an array is using their index, like books on a library shelf.

Accessing array data requries the index to be specified. The index starts at zero, so if you want the 3rd item of the Cars array, Cars[2] will give you it.

A function is a bunch of code that you will be using a few times. When called upon, a function can be given new parameters to complete a repetitive task. A good analogy for this is an astute kitchen hand. Without functions, the kitchen hand is told how to cut carrots, but then needs to be told how to cut peppers and potatoes. With functions, the kitchen hand is taught how to cut vegetables and uses this method to cut carrots, peppers and potatoes.