Comm Lab Networked Media Week 2

JavaScript

JavaScript is a scripting language that is typically used on web pages where it runs client-side (within the web browser). It is a general purpose language with a lot of built-in functionality for interacting with elements on a webpage and responding to actions initiated by the user.

Although the JavaScript has "Java" in it's name, it isn't related other than by the fact that it looks something like Java. JavaScript's official name is ECMAScript (ECMA is the European Computer Manufacturers Association, a standards body). It was initially created by Netscape Communications.

More Information:
JavaScript - Wikipedia

Script Tag

JavaScript can be placed anywhere within an HTML document, although it is typically included in the "head" section of the HTML, and is specified by the use of <script> tags:

<html>              
	<head>              
		<script type="text/javascript">              
			//JavaScript goes here

		</script>
	</head>              
</html>              
		

You can also write JavaScript in file external to the HTML and point to that file in a "script" tag.

<script type="text/javascript" src="myscript.js"></script>
		

Comments

Comments in JavaScript are similar to comments in Java or C:
	<script type="text/javascript">              
		// Single Line Comment        
		/* 
			Multiple
			Line
			Comment
		*/
	</script>

Console

One of the first things we probably want to learn is how to get debugging output. You can write to the "console" by using the built-in console.log method:
console.log("Hello");
In order to see the console on Chrome, select "View", "Developer", "JavaScript Console". Use it often!

Variables

Variables are containers for data. Essentially a variable is something that can hold a value and that value can be changed (They can vary):

var something = "Hello";
console.log(something);
		

Data Types

Variables in JavaScript (and many other scripting languages) are loosely typed and do not need to be declared with their type. The data that the variables contains does have a type.

Other languages such as Java are strictly typed and each variable must declare the type of the data it will contain.

Regardless of whether or not JavaScript is loosely or strictly typed we still need to be aware of the types of variables that JavaScript understands:

  • Number - A number with a decimal point. In other languages this is typically called a float. var anumber = 5; or var anothernumber = 1.223;
  • String - A series of characters. These can be defined with either single or double quotes. var astring = 'Hello'; or var anotherstring = "Til tomorrow";
  • Boolean - A "True" or "False" value. var aboolean = false; or var anotherboolean = true;


  • For comparison, this is the set of data types available in Java (and many other languages):

  • integer - A whole numbers. int someint = 5;
  • boolean - True or False. Often the result of an expression. boolean somebool = true;
  • float - A number with a decimal point. 1.5, 3.987 and so on. float somefloat = 99.76;
  • byte - An 8 bit value. Ranges from -127 to 128 in value. byte mybyte = -90;
  • char - A single character. char mychar = 'A';
  • (You notice that in Java you include the "type" when declaring the variable.)

    Since JavaScript is loosely typed, you can do this:

    var anothervariable = "My Name Is Shawn";
    console.log(anothervariable);
    anothervariable = 15;
    console.log(anothervariable);
    		
    More Information:
    JavaScript Data Types

    Assignment

    Once they are declared, you are free to assign values to them and subsequently use them in operations:

    var myinteger = 5;
    myinteger = 5 + 5;
    myinteger = myinteger - 5;
    var yourfloat = 5.5;


    An example:
    		
    	<script type="text/javascript">
    		
    		var avariable = 0; // Assigns 0 to be held by a variable named "avariable".  The name can be anything you want it to be.
    		avariable = "something else"; // Changes what "avariable" holds by assigning it to be "something else".  Also switches it's type.  Don't need to use "var" again as avariable is already declared.
    		
    		console.log(avariable); // This is a function which we can use to display something in a pop-up alert box.  We'll get to functions more next week but this is one we need for now.
    	
    	</script>
    

    alert()

    alert is a built-in function that generates an alert box containing whatever you put in the parenthesis. Technically it is window.alert but with function that references "window" we don't need to include "window.". We'll cover this more as we get into Functions and Objects.
    	alert("My Name Is Shawn");
    
    One of the more interesting things about the alert function is that it pauses program execution until the user responds to the alert. This can be useful in development but probably not so useful in production.

    Statements

    In the above variables section, you may have noticed that the JavaScript statements ended with a semi-colon:
    		
    	var myname = "shawn";
    

    This isn't always required but the rules can sometimes be confusing so it is easiest to just include them at the end of a statement.

    More Information:
    Your Guide to Semicolons in JavaScript

    Operators:

    Assignment:
    =

    Mathematical Operators:
    +, -, /, * (addition, subtraction, division and multiplication)

    Example:
    var anumber = 0;
    anumber = anumber + 1;
    console.log("anumber = " + anumber);
    anumber = anumber + anumber;
    console.log("anumber = " + anumber);
    anumber = anumber/2;
    console.log("anumber = " + anumber);
    anumber = 7 * 8;
    console.log("anumber = " + anumber);
    
    anumber++;  // Short-cut for adding one, called "increment"
    console.log("anumber = " + anumber);
    anumber--; // Short-cut for subtracting one, called "decrement"
    console.log("anumber = " + anumber);
            
    Relational Operators:
    >= (greater than or equal to)
    <= (less than or equal to)
    == (equality)
    != (inequality)
    === (equality with type checking)
    !== (inequality with type checking)

    Logical Operators: Sometime called boolean logic
    || (logical OR)
    && (logical AND)
    ! (logical NOT)

    Truth tables:
    Logical operators follow the following rules when evaluating to "true" or "false".
    OrTrueFalse
    Truetruetrue
    Falsetruefalse

    AndTrueFalse
    Truetruefalse
    Falsefalsefalse

    Conditionals

    Execute a block of code based on the result of an expresssion that utilizes relational or logical (boolean) operators

    If Statement:
                var anint = 1;
                if (anint >= 0)
                {
                    // Execute some code
                }
            


    If Else Statement

                var anint = 1;
                if (anint >= 0)
                {
                    // Excute some code
                } 
                else
                {
                    // Execute some other code
                }   
            

    If, Else If, Else

                var anint = 1;
                if (anint >= 0)
                {
                    // Execute some code
                }
                else if (anint < -1)
                {
                    // Execute some other code
                }
                else
                {
                    // Execute this code if none of the other conditions are true
                }
            
    You can use the boolean operations to use boolean logic on multiple expressions.
                var anint = 1;
                var anotherint = 2;
                if (anint > 0 && anotherint <= 2)
                {
                    // Execute some code
                }        
             

    Indentation:

    Notice above how I indent code that is within the blocks (within "{ }"). This is purely for readability and understanding. Do it, you will thank me later.

    Loops

    While

    Just as with our conditional (if / else) statements a while loop employs boolean test that must evaluate to true in order for the instructions enclosed in the curly brackets to be executed. The difference is that the instructions continue to be executed until the test condition becomes false.
    var x = 0;
    while (x < 10) 
    {
    	console.log(x + " is less than 10.<br />");
    	x++;
    }
    

    For

    Since this is a common use of a loop (creating a variable, checking it's value and incrementing by a certain amount) there exists an even quicker way to do the above, all in one step.
    for (var x = 0; x < 10; x++)
    {
    	console.log(x + " is less than 10.<br />");
    }
    
    You can read this as, create variable x and set it to 0, while x is less than 10, do the following. Increment x by 1 at the end.
    Exactly what we are doing in the while loop but in one quick step.

    Functions

    A function is a reusable chunk of code. It is a way to encapsulate a set of instructions so you can run them when you want or run them over and over again.

    You define a function in JavaScript like this:
    	function aFunctionName()
    	{
    		// Some code to execute
    	}
    
    Begin with the word "function" and then name it. The parenthesis allow you to take in "arguments" which are variables that can be used within the function.

    A very simple function:
    	function writeAndAlert(whattowrite)
    	{
    		alert(whattowrite);
    		console.log(whattowrite);
    	}
    
    You can call this function anywhere in your code (after you have defined it):
    	writeAndAlert("Hello Hello");
    
    Creating your own functions

    function dosomething(somedata)
    {
    	var whattosay = "Hi there " + somedata + " , nice to meet you!";
    	alert(whattosay);
    }
    		
    As you can see, the + symbol string concatenation.

    You would run this function with something like this:
    dosomething("shawn");
    		
    You can also write a function like this, assigning it to a variable to illustrate the fact that it is a variable.
    (There is more to this but we'll talk about it another time)

    var dosomethingelse = function(somedata) {
    	var whattosay = "Hi there " + somedata + " , nice to meet you!";
    	alert(whattosay);		
    };
    		

    Variable Scope

    Variables that you declare inside a function (and in other languages inside any block of code) are local to that function.

    If I have a function called blah and inside blah I declare a variable called "counter", I can not refer to counter outside of the function. In the case that I want to use the value of counter outside of the function, I either have to declare it outside of the function or return it's value.
    	var aGlobalVariable = "Global";
    	
    	function globalLocalTest()
    	{
    		var aLocalVariable = "Local";
    		
    		alert("Inside Function Global: " + aGlobalVariable);
    		alert("Inside Function Local: " + aLocalVariable);		
    	}
    	
    	globalLocalTest();
    	
    	alert("Outside Function Global: " + aGlobalVariable);
    	alert("Outside Function Local: " + aLocalVariable);		// This may not even appear
    

    p5.js

    p5.js is a sort of port of Processing to JavaScript. It isn't strictly a port as it has some differences and of course works more like JavaScript in a browser than a straight port of Processing would. This is a good thing!

    The p5.js Get Started page is a great place to do just that. In short, we need to download the library and then include it with script tag in our HTML:

    <script type="text/javascript" src="p5.min.js"></script>
    		
    Once we do that, we can use another script tag to create our sketch. There are two functions that we should implement to work with p5.js, "setup" which is run once when the page loads and "draw" which is run over and over again in a loop:
    		
    		<scipt type="text/javascript">
    			// Runs once at the start
    			function setup() {
    
    			}
    
    			// Runs in a loop, over and over again
    			function draw() {
    		
    			}
    		</script<
    		
    p5.js is great for drawing on the page. It uses the HTML5 Canvas element under the hood.

    The p5.js reference is a great place to start looking at the various features. Let's start with these:

    createCanvas
    mouseIsPressed
    point, line, background, fill, noStroke, rect, rectMode, ellipse, ellipseMode, triangle