---
# System prepended metadata

title: 'TINKER: Javascript, Part I Notes'

---

# TINKER: Javascript, Part I Notes

NOTES
--
I wasn’t sure whether to include this supplementary reading as part of the Tinker or a separate document. But here it is. You can read it first, but it probably would help to at least scan through the Tinker questions so as you read this, you can think of the Tinker questions as a context and how they relate, to make sense of some of these extras I’ve included.

Programming Overview
You’ve already “coded” things. HTML/CSS is a way to code web-documents for consuming in browsers, and style documents for declaring how style rules apply to your web-documents. You’ve learned that there is structure to code, hierarchy and sequence to code, syntax to code, that specific important keywords mean something in code. Now, we’re going to go further and start to “program” things using these principles, and then some.

Programming is just a set of instructions (through code) to tell the computer how to execute a particular task, a series of routines. There is syntax involved (as defined by the Javascript language) and logic involved (how things should happen, when). This is what really makes the web so powerful - with programming, we can make things react to users, produce human-computer interactions, hopefully in joyful ways.

How to think about programming
I’ve been thinking about this one a lot. And from my years of experience, I’ve kind of distilled it down to three things you should be thinking about with every little thing you learn about programming. Really, these are the golden questions you should ask anytime you are writing, reading, studying programs. That is:

What is the STATE of the program?
What is the SEQUENCE of the program?
What is the CAUSALITY of the things in the program?
That’s really it. If you do the following things, pretty much you can start to break problems down into manageable parts, as well as ask the right questions when it comes to figuring out parts you don’t understand.

STATE
the particular condition that something is in at a specific time

You can imagine that when you visit Facebook for the first time, the program is at a certain zero state. You see a splash page and some marketing to get you to sign up. This state is easy to imagine as you can visually think of the state of the program.

But what you are now trying to see as a programmer, is how the state might be defined beyond the surface of what you can see. For example, we might represent this state as the result of some code like this:

var loggedIn = cookie.authentication;

if (loggedIn === true) {
  showUserFeed();
} else {
  showSplashPage();
}
Since we’re on the splash page, you can imagine that the state of the program, more specifically, the state of the variable loggedIn is false. If they were already logged in, you could imagine the state of the program starting with loggedIn === true and therefore, pushing the displayed state to the user feed.

Let’s say that the user doesn’t have an account. We could say that the state of the program is that var user = undefined;

Let’s say the user starts filling out the signup form and each time they fill in one item, we update the state of the user:

user.firstName = "Santa"; State of user (firstName) updated.
user.lastName = "Claus"; State of user (lastName) updated.
Each time this user data is updated, we are changing the state of the program. And through these states and assignments of states we can push how the program looks and behaves. For example, if the user leaves the page and comes back, maybe we want the program state not to start back at zero, but to start where the user left off.

States are represented by variables. You set variables to save the state of a particular program. This data that represents a certain state of a program can then be used to do something about it. That is, to cause an update in the way the page looks or behaves as demonstrated in the above example.

So the takeaway: When you are learning this stuff, each line, each routine, each little part of a routine, you should be asking yourself:

What is the state of the variables?
What is the state of the program?

SEQUENCE
a particular order in which related events, movements, or things follow each other.

We’ve already established how sequence can have an effect on HTML/CSS. As a matter of fact, in Javascript sequence also has an important role. In general, code runs from top to bottom, left to right. However, with programming we have the ability to make for much more sophisticated, and dynamic sequences of things to happen.

var userTopicPrefs = [];

if (userTopicPrefs.length > 0) {
  showPinboard(userTopicPrefs);
} else {
  showTopicPicker();
}
In the above code, based on the user’s topic preferences we influenced the sequence of routines to happen. Since the user has no preferences (an empty array) we bypased the routine to show the pinterest like pinboard via showPinboard() and instead went to a “pick your topic preferences” interaction via showTopicPicker().

Take a look at the following code:

<input type="text" onchange="updateComment(event)" />
<button onclick="postComment()">SAVE</button>
var comment = undefined;

function updateComment(event) {
  var inputElement = event.target;
  comment = inputElement.value;
}

function postComment() {
  // get comment data and save it to the database
}
In this example, when the text input changes value (user fills it in) the updateComment function is called updateComment(). This sets the state of the comment variable to whatever text the user wrote in the input.

The postComment function is called postcomment() when the html button is clicked. And we could get the state of the comment variable and send that data to the database.

We could say that the intended sequence of this is:

User types in text
change event triggered
updateComment() called with event data passed in as argument
updateComment routine begins
inputElement is set to the HTML input element, via event property of target
comment is set to the text, via the value property of inputElement
updateComment routine ends
User clicks on the button
click event triggered
postComment() function is called
postComment routine begins
comment state is the user text and sent to the database
postComment routine ends
However, what if the user clicks on the SAVE button before they enter any text in the input?

Sequence is more than just the order in which you write your code. When a function is called will change the sequence of what routines, and sub-routines execute. When you have user interactive things (like button clicks) the sequence can change depending on when a user triggers an interactive event. Sometimes, some code might not happen at all. These are all things you need to think about very explicitly and conscientiously.

What are the independent groups of code sequences (routines) in my program?
How will the STATES and EVENTS affect the SEQUENCE of the program?

CAUSALITY
You can’t really mention programming without addressing causality. And in our prior work, we’ve been very adamant about seeing and understanding the causality of things we do. It may seem obvious, but we program things in order to cause things to happen. Mostly, it’s about causing:

Changes to the STATE of the program
Changes to the SEQUENCE of the program
To be honest, I can’t think of anything else any line of code would do. Even things like using code to GET the state of a program, is usually for the purpose of eventually changing the state of the program.

This third golden principle of programming ties the two other golden principles together. Programming is by nature, a very explicit exercise. Understanding how each part of a program, from the higher level logic to the lower level syntax, causes the program to work in a certain way is the key. Each rule in programming usually is tied to a SINGULAR result. Programming has very little ambiguity in that regard. You tell the computer precisely what you need it to do in a very exact way, or it won’t work. Ambiguity, is for the humans.

What does this program routine cause?
What does this part of the routine cause?
What does this syntax: symbol, operation, pattern cause? (low-level)

Ask yourself questions regarding these three golden rules with each line of code you write and you should be on your way to understanding it in a more systematic manner.

FUNCTIONS: Inputs and Outputs
Arguably, the biggest problems I see when students are learning functions are the conceptual understandings around the following things:

Understanding a function declaration vs. a function call.
Understanding function sub-routines in the context of a larger sequence.
Understanding the difference between parameters and arguments in relation to INPUTS.
Understanding the return keyword in relation to OUTPUTS.
Declaring and Calling Functions
Declaring a function is telling the computer: “Remember this code and run it when I tell you to in the future.”

Calling a function is telling the computer: “Remember that code? Run it now.”

Declaring
To setup a function, you have to declare a function. That’s about it. There is one key giveaway that something is a function declaration. That giveaway is the keyword function. Also note, that when we declare a function we also define it as a block of code to run. The giveaway here is the opening and closing curly-braces {}.

// Function declaration and definition PATTERN

function funcName(params) {
  // sub-routine defined
}
function doSomething() { ... }
Do you see the keyword function above? Yep, it’s a declaration. Won’t execute on its own but you essentially told the computer to be ready for the future.

var doIt = function() { ... };
Do you see the keyword function above? Yep, it’s a declaration. Won’t execute on its own but you essentially told the computer to be ready for the future. This function doesn’t have a name like the first example (i.e. doSomething). It has a reference to it, via the variable doIt. But it is nameless. We call this an anonymous function. The variable doIt becomes the inferred name. For the most part, you can treat these similarly although there are some caveats which we might discuss later.

How about this one?

doIt();
Nope. There is no function keyword. Here we are not declaring a function. We can assume it was already declared prior, or maybe declared as a default with the browser, which comes with a set of functions already declared and usable for us.

Let’s look at a stranger example:

setInterval(function() {
  // code
}, 1000);
Do you see the keyword function above? Kind of?

Here there are actually two functions. The first is a function named setInterval, the second is an anonymous function that we happen to declare right there. Having trouble seeing these two? Let’s separate them a little bit so you can see.

setInterval( ___ , 1000);

function() {
  // code
}
setInterval is a function given to us by default. It has already been declared somewhere by our browser. Notice there is no function keyword associated with it. Here we are actually calling the function.

The second function is anonymous. There is no name given to it. But it is a function and it is being declared right there inside the call. Again, the key point is to see the keyword function and know that you are declaring a function, and that you have defined a function.

What does this do? setInterval is basically a timer. It accepts two parameters. The first argument must be a function and second is a Number. Basically, setInterval needs a function that will be used every X milliseconds. Thus, in this example the function will run every 1 second interval. Every second, internally, setInterval will call the function you passed in. Thus, it is convenient for us to declare a function right within the setInterval call, giving us this funny looking but common format. We could have easily rewritten this like the following:

function moveClockSecHand() {
  // code to move the second hand of the analog clock
}
setInterval(moveClockSecHand, 1000);
It’s the same as above, except we declared a named function on the lines prior, and passed that function into the setInterval as an argument through the reference.

Calling
To use a function, you have to call a function. There is one key giveaway that something is a function call. That giveaway is that you see parentheses () immediately after some reference and there is no keyword function. The pattern to call a function is the following:

funcName();                // Without arguments

funcRef(argA, argB, ...);  // With arguments
If you see something() or something(arg, arg) or something like that you are calling an already declared function. You might have declared it yourself, it might come from the default, it might come from a library like Bootstrap.

You’ll also notice that we don’t have curly-braces {} when calling a function. Makes sense since curly-braces are for blocking off and defining the code to be run. Since we’ve already done that, when you call a function you won’t see any {}.

doSomething();
Do you see the keyword function above? Any {}? No. So it’s not a declaration. Does it fit the pattern of something()? With () right after the function name? Yup. Thus, here we are calling the function, telling the computer to execute it as it was declared and defined earlier.

doSomething("Thomas");
Does it fit the pattern of a function call? Yes. Do you see a function keyword or {}? No. Here, we are calling the doSomething function and passing in the argument "Thomas" which, depending on how the function was declared - will probably do something with the input.

doSomething;
Do you see the keyword function above? No. So it’s not a declaration. Do you see any () following this reference in the pattern of something()? No. So we are not calling a function either.

Here, this is essentially a variable. Much earlier in this section, we did declare it and define it. So we can say that the variable doSomething just points to a function. doSomething is a function. But the declaration happened way earlier, and it is not being called right now.

Thinking of Function Sequence as Sub-routines
A function is basically a block of code, a sub-routine that will execute when you call upon it to do so. Take a look at the following routine.

function setName(someName) {
  myName = someName;
}

var myName = "Anonymous";

setName("George Washington");
myName = "Valentina Tereshkova";
setName("Mark Twain");
You can think of the sequence of this routine as executing top to bottom. But keep in mind that the code inside the function setName is a sub-routine of the larger code. That sub-routine does not actually happen until the function is called upon setName(...). So the order of how this code happens is the following:

Line 1 - function is declared.
Line 5 - variable is declared and assigned a value.
Line 7 - function is called.
Line 2 - sub-routine executes.
Line 8 - variable is assigned a value.
Line 9 - function is called.
Line 2 - sub-routine executes.
Paramters vs. Arguments as INPUT
A parameter is a variable in a function definition.

An argument is the data you pass into the function’s parameters, when a function is called.

Here is the pattern to understand this:

var kelvin;

function celciusToKelvin(celcius) {
  kelvin = celcius + 273.15;
}

celciusToKelvin(0); // kelvin = 273.15
We declared and defined the celciusToKelvin function on line 3. Inside the (), celcius is the parameter, a variable name we made up.

0 is the argument we pass into the function when we call it on line 7.

We could have defined the parameter like this:

function celciusToKelvin(c) {
  kelvin = c + 273.15;
}

celciusToKelvin(-273.15); // kelvin = 0

// OR this in honor of Hawaii's official State Fish

function celciusToKelvin(humuHumuNukuNukuApuaA) {
  kelvin = humuHumuNukuNukuApuaA + 273.15;
}

celciusToKelvin(100); // kelvin = 373.15
The computer doesn’t care how we define our parameters when we declare and define our function. These variations are essentially the same as the original. What is important is that we give the parameters, variable names that makes sense; because as you can see, it is how we access the data that is passed into the function for use internally by the function.

What people tend to mess up most is that they see an example with a parameter defined a certain way. Then they think that parameter name is something special like a keyword. You might call it celcius, I might call it c. Strange people might name it after a fish. A common example that messes people up:

Finally, you can pass data in as arguments by reference of course.

var myApartmentTemp = 20;
var someTemp = myApartmentTemp;
var x = someTemp;

celciusToKelvin(x); // kelvin = 293.15
Return as function OUTPUT
Get data back, where the function was called.

Sometimes functions have OUTPUTS. What people confuse is output in terms of data vs. output in terms of behaviors.

For example:

function hello() {
  document.write("Hello");
}
Many people have the misconception that the output here is "Hello". This may make sense from a user perspective, it is not what we mean by output from a programming perspective. For example, using the above code if I did something like the following:

var message = hello() + " World!"; // "undefined World!"
message would not be set to "Hello World".

Our hello function never had any data output. It probably sent data to the screen and printed “Hello” on the page somewhere. But it didn’t have a functional data output.

The key point here is when we talk about functions and output, we are really talking about using the keyword return.

Return data back to where the function was called.

For example:

var first = "Jean Luc";
var last = "Picard";

function makeFullName(first, last) {
  return last + ", " + first;
};

var username = makeFullName(first, last); // Picard, Jean Luc
makeFullName formats the name and returns a string “Picard, Jean Luc” to where it was originally called. That is, the right side of = operator. username is set to this value.

Or another:

function hello() {
  return "Hello";
}

var message = hello() + " World!"; // "Hello World!"
Our function hello returns data back to where it was called. The way to think about the above example, line 5 is like this.

Right side looks like:

  hello() + " World!"

Evaluate the right side:
  Evaluate the function call, hello()
    returns a string "Hello"
Right side now looks like:

  "Hello" + " World!"

Continue evaluating right side:
  Concatenate "Hello" + " World!"
Right side now looks like:

  "Hello World!"

Assign the variable message to "Hello World!"
Take a look at this example:

function halfLife(materialVolume) {
  return materialVolume / 2;
}

var volume = 100;

halfLife(halfLife(halfLife(volume))); // 12.5
Since the function halfLife will always return a number, we can call it and use the return output number as the argument for the next call. On line 7, we do this 3 times to get 12.5.

As a rule of thumb, if you want your function to have an output, so that you can use that output to construct more sophisticated statements, use the keyword return and be aware of what kind of data you are returning.

HTML and Javascript
There are a few key concepts that I want you to understand for this Tinker, with regard to how HTML and Javascript relate.

The point of Javascript, is to “connect” with HTML. That is, we basically use Javascript to manipulate our things on our HTML page. As we have learned:

HTML is a language that represents the structure and organization of a web-based, browser readable document.
It consists of things like elements and text nodes that are structured in a parent-child hierarchy.
These things have attributes and values that further shape how these things are represented.
<!-- Within larger HTML Document -->

<div id="kittens" class="cute meow">
  <img src="images/meowth.jpg" />
  <img src="images/purrrr.jpg" />
  <p>
    I really like <span>fluffy</span> kittens.
  </p>
</div>

<!-- Pattern of HTML Nodes -->
<element attrA="valueA" attrB="valueB">
  <element attrC="valueC"/>
  <element attrD="valueD"/>
  <element>
    Text Node <element>text</element> text.
  </element>
</element>
Javascript can read/access the page by selecting elements:

var kittenDiv = document.querySelector('#kittens');   // An element: div#kittens
var imageElements = document.querySelectorAll('img'); // List of elements: [imgA, imgB]
Javascript can read/access properties of elements:

document.querySelector('#kittens').id;   // "kittens"

document.querySelectorAll('img')[0].src; // "images/meowth.jpg"
document.querySelectorAll('img')[1].src; // "images/purrrr.jpg"
Javascript can read/access other useful properties of elements:

// I'm use "el" as shorthand for "element", a common convention.
var el = document.querySelector('p');
var myText = el.textContent;  // "I really like fluffy kittens."
var myHTML = el.innerHTML;  // "I really like <span>fluffy</span> kittens."
Javascript can traverse the document structure:

var imgOne = document.querySelectorAll('img')[0]; // <img src="images/meowth.jpg" />
var imgTwo = imgEl.nextElementSibling;            // <img src="images/purrrr.jpg" />

var spanEl = document.querySelector('span');      // <span>fluffy</span>
var pEl = spanEl.parentElement;                   // <p>I really like <span>fluffy</span> kittens.</p>
Javascript can manipulate elements:

var imgOne = document.querySelectorAll('img')[0].src; // "images/meowth.jpg"
    imgOne.src = "images/nyancat.jpg";                // "images/nyancat.jpg"

var kittenEl = document.querySelector('#kittens');
var kittenClasses = kittenEl.className;               // "cute meow"
var kittenClassList = kittenEl.classList;             // ["cute", "meow"]
    kittenClassList.add("hungry");                    // ["cute", "meow", "hungry"]
    kittenClassList.remove("cute");                   // ["meow", "hungry"]
    kittenClasses = "dogWasHere";                     // className "dogWasHere", classList ["dogWasHere"]
And when you do these things, your page will dynamically change.

Javascript Events
Javascript, also makes it possible to react to user actions. Common actions are things like:

Clicking the mouse
Pressing a key
Scrolling a mouse wheel
Pinching on mobile
Value changes on forms
These things are called events and there is pattern to how you go about hooking up your JS to these things. That pattern is you need to:

Listen for a specific event
Trigger an event (often by the user actions)
Handle what to do when the event is triggered
There are a few ways to get your page to listen for events but the one we’re using for now is to use HTML markup to tell the page what to listen to.

<div onclick=""></div>
<textarea onkeypress=""></textarea>
<input onchange=""/>
This on event, rather onevent pattern works for many different kinds of events. What we are doing here is setting a listener for that particular event on that particular element. div will do something when it is clicked. textarea will do something when key is pressed. input will do something when the value changes.

Thus, the event part of it is triggered by the user actions.

Finally, what then happens? We need to handle these events. That is, when an event occurs, we need to tell it what function to call. That function is referred to as a handler function. In the above example, you’ll notice that the values are all empty. This is where we will tell HTML what the handler should be.

Declare the printGreeting function.

function printGreeting() {
  // sub-routine to print greeting
}
Attach handler to event. Call printGreeting() handler function when click event is triggered.

<div onclick="printGreeting()"></div>
This onclick attribute and printGreeting() value - an event handler call, is the connection between your HTML and JS.

It’s worth noting here that when events happen, you might want to know something about the event in your handler function. For example, what kind of event was triggered? What key was pressed? What element was it that triggered the event? (You can have multiple elements share the same handler function).

To deal with this, you can design your handler function to accept a parameter that represents the event data. If you do this, when you call the handler you would pass in an argument representing the event data. For example:

Declare the printGreeting function with a parameter to accept event data.

// "e" is an arbitrary name representing the event data
function printGreeting(e) {
  e.target; // element that the event handler was attached to
  e.type;   // "click"

  e.target.innerHTML = "<strong>Hello World!</strong>";
}
Attach handler to event. Call printGreeting(event) handler function with event data passed into function when click event is triggered.

<!-- Call printGreeting and pass in event argument -->
<!-- Here you must use the exact word: event       -->
<div onclick="printGreeting(event)"></div>
I want you to study this pattern and recognize where I’ve used this throughout this Tinker exercise. You should take the process concept: listen, trigger, handle and map it to your understanding of HTML and JS functions. If you can understand this pattern, you’ll be able to apply it to all these interesting categories of events Events. Some of the ones you might find interesting are:

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
https://developer.mozilla.org/en-US/docs/Web/API/InputEvent
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
Take a look at some of the properties available to you through the event argument. For example, event.type (I used e.type in the example above) is a generic property of all Events. But if you go into MouseEvents you’ll find that there are special properties for mouse events like the click coordinates X and Y. Browse through it and finding linkages between the docs and the examples provided in this exercise.