1 of 47

All About JavaScript

var, loop, functions and the art of debugging

1.31.2018 // DataViz for Arch, Urbanism, Humanities

2 of 47

First things first: Syntax

3 of 47

  • Whitespace does not matter,

but upper/lower case DOES matter.

  • Comments
  • Literals
  • Constants
  • Reserved Words

4 of 47

5 of 47

Reserved word

Comment

Literals

6 of 47

Comment

Constant

7 of 47

Variables

8 of 47

Variables

  • Are like math— var x = 6;
  • Are a way to store stuff.
  • Can be different types of stuff
    • Number, String, Boolean, Array (today)
    • Objects (we’ll cover next time)
  • JavaScript is pretty flexible about data types.

9 of 47

How to make variables

  • Declaration— create a variable (no value yet)

var blackjack;

  • Assignment— set the value

blackjack = 21;

  • Declaration and assignment in one line—

var blackjack = 21;

10 of 47

Numbers represent numerical data

Integer: 75 or Float: 3.14159

Strings are used for storing textual information

"a name means a lot just by itself"

Booleans* represent a binary value

true or false

Arrays store multiple variables together

[ 1, 1, 2, 3, 5, 8, 13, 21, 34,... ]

11 of 47

Numbers

  • You can set variables to numbers and perform basic math operations
    • Add +
    • Subtract -
    • Multiply *
    • Divide /
  • Try!

console.log(3.14 * 57);

12 of 47

Some Math Functions

  • Get a number between 0 (inclusive) and 1 (exclusive)

console.log(random()); // prints 0.1734...

  • Get a number between two values

random(10, 20); // prints 14.493...

  • Round up

ceil(3.14159); // prints 3

  • Get a random integer between two values

floor(random(-10, 50)); // prints 23

13 of 47

14 of 47

15 of 47

String

  • Strings are sequences of characters**
  • Basically, strings are words or a bunch of letters.
  • Strings are defined with quotation marks, either single or double:

var name1 = 'Harry Potter';

var name2 = "O'Malley";

// ^ can't use single quotes here

// because of apostrophe

16 of 47

**On Characters and Encoding

  • Every character is represented by an underlying code. The historic American code is “ASCII”, where ‘A’ is 065 and ‘a’ is 097.
  • Obviously we rapidly run out of numbers to cover all the characters in the world. Enter Unicode: every character, including emoji and foreign language characters are assigned an underlying id that looks something like U+1F923, which happens to be . Sadly, p5.js isn’t Unicode-compliant even though Sublime is, so even if you enter an emoji you’ll see something like ☺啥 printed out.)

17 of 47

Arrays

18 of 47

An array is...

  • A storage structure for multiple pieces of information,...
  • where each piece of info is in a numbered position (index), and...
  • a specific piece of info can be retrieved by its index

19 of 47

var name = "Hermione Granger";

var age = 13;

var courses = ["Astronomy",

"Arithmancy",

"Ancient Runes",

"Care of Magical...",

"Muggle Studies",

"Potions",

"Divination" ];

20 of 47

Notes on array syntax...

  • Enclosed by square brackets— [].
  • Items separated by commas— [ "Harry", "Ron", "Hermione" ]
  • No comma after the last item. An array of one element— [ "Voldemort" ]
  • Arrays can hold any kind of data, not just strings. An array of numbers stored in a variable—

var scores = [17, 23, 25, 29, 37];

  • The numbering of items, the index, starts at 0.

21 of 47

Conditionals: if, else, else if

22 of 47

Sometimes we want to describe behavior like—

If I am hungry then eat some food, otherwise if I am thirsty, drink some water, otherwise, take a nap.

In drawing we might have something more like—

If mouse is inside the circle, color it green, otherwise color it red.

23 of 47

Many tasks require conditional control, aka ability to react differently based upon what happens. “If user does A, produce X behavior; if user does B, produce Y response instead.”

To do this, we use booleans that store truth values and if-statements which do conditional action based on a boolean value; i.e. depending on the condition, execute different code.

24 of 47

If-statement syntax:

if (BOOLEAN_EXPRESSION) { // aka "test expression"

STATEMENTS_IF_TRUE // aka "then branch"

} else {

STATEMENTS_IF_FALSE // aka "else branch"

}

  • The boolean expression needs to be in parentheses.
  • The else part is optional: skip it if you don’t need to do anything in the else branch.

25 of 47

Relational operators, for numbers*

num < 50

Less than

num <= 23

Less than or equal to

num == 57

Equal to (Note: == tests equality, = assigns a value!)

num != 17

Not equal to

num > 110

Greater than

num >= 42

Greater than or equal two

*Next week we’ll talk about comparing strings

26 of 47

Loops, or Iteration

27 of 47

ellipse(1, 100, 10, 10);

ellipse(50, 100, 10, 10);

ellipse(100, 100, 10, 10);

ellipse(150, 100, 10, 10);

ellipse(200, 100, 10, 10);

ellipse(250, 100, 10, 10);

ellipse(300, 100, 10, 10);

ellipse(350, 100, 10, 10);

ellipse(400, 100, 10, 10);

ellipse(450, 100, 10, 10);

ellipse(500, 100, 10, 10);

ellipse(550, 100, 10, 10);

ellipse(600, 100, 10, 10);

ellipse(650, 100, 10, 10);

28 of 47

Loops are about repeating a set of instructions.

  • Repeat X number of times
  • Repeat until Y condition is met

For example:

  • Draw a circle. Repeat 15 times.
  • Draw a circle, 10px offset from the one before, until you reach the edge of the screen.

29 of 47

Basic components of a for-loop

for (var i = 0; i < 100; i++) {

line(0, i, 10, i);

}

command

counting variable

# of times to repeat

What this does: draw 100 horizontal lines, 1 line per pixel, starting at top of canvas.

30 of 47

For-loop repeats instruction until condition is satisfied

for (var x = 0; x < width; x = x + 50) {

ellipse(x, 100, 10, 10);

}

Initial state

condition to satisfy,

a.k.a.“repeat until this is true”

change after each repetition

What this does: make ball elements, 50px apart, until the edge of the screen

31 of 47

A note on “shorthand”...

for (var i = 0; i < 100; i++) {

line(0, i, 10, i);

}

???

for (var x = 0; x < width; x = x + 50) {

ellipse(x, 100, 10, 10);

}

change after each repetition

32 of 47

Increment and decrement are just shorthand ways to write out “add one” or “minus one”:

  • Increment—

myNum = myNum + 1;

myNum++;

  • Decrement—

n = n - 1;

n--;

33 of 47

Functions

34 of 47

function myFunc(a, b) {

/* do some computation... */

return r;

}

INPUT x

FUNCTION f

OUTPUT f(x)

Functions are a method of abstraction.

35 of 47

Functions by analogy:

… like a recipe, say for chocolate cake

… like a machine, a blender

… like a workspace, a kitchen with its own storage space

Combined: a function is like a kitchen with a chef inside, customers who eat food that comes out of the kitchen don’t need to know anything about how it works.

  • Inputs: eggs, flour, cocoa
  • Output: chocolate cake

36 of 47

Anatomy of a function

function draw() {

ellipse(x1, y1, 100, 200);

}

name

parameters (none!)

name

parameters (4)

37 of 47

Drawing a blue circle without a function—

fill('#8470ff');

ellipse(50, 50, 20, 20);

… // draw other shapes

fill('#8470ff');

ellipse(480, 23, 20, 20);

… // draw other shapes

fill('#8470ff');

ellipse(42, 280, 20, 20);

38 of 47

Drawing a blue circle with a function—

function draw() {

drawBlueCircle(50, 50);

… // draw other shapes

drawBlueCircle(480, 23);

… // draw other shapes

drawBlueCircle(42, 280);

}

function drawBlueCircle(x, y) {

fill('#8470ff');

ellipse(x, y, 20, 20);

}

39 of 47

40 of 47

Variables Scope

41 of 47

Variables have global or function scope.

Global variables can be used anywhere in program.

Variables declared in a function can only be used locally, within that function.

If, inside a function you declare a variable with the same name as a global variable, the program will calculate with the value of the function variable within the scope of the function.

42 of 47

Global variables

Local variables

43 of 47

44 of 47

The art of debugging

45 of 47

  • Write pseudo code (pro-tip: do this on paper)
  • console.log() is your friend (always know your state)
  • Simplify (write pseudocode)
  • Take a break, ask a friend
  • Start early

Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law. —Gödel, Escher, Bach

46 of 47

Make background green

Set fill to yellow

Draw rectangle with fixed X1, Y1, X2, but map Y2 between 0~400 depending on # seconds.

Scale everything 11x.

Draw a circle of fixed size.

Reset everything back to 1x scale.

47 of 47

End.