Introduction to Programming

Hello, World

var message = "hello, world";
log(message);

A Little About Computers

Computers are incredibly dumb

  • They can only perform very simple operations
  • They have no ability to make inferences or assumptions
  • They only do what they are told

However

  • Computers can do billions of operations a second

Telling Computers What To Do

Surprise! We do this using a program.

  • A schedule of operations for the computer to perform.
  • Similar to television "programming".

Earliest Programs

Programs actually predate electronic computers.

Some of the earliest programs were written for machinery such as looms (check out the Wikipedia article on the Jacquard Loom). The sequence of operations to run were often encoded onto punchcards which were fed into the machine.

Machine Code

With the invention of electronic computers around the 1940s, modern programming began to take shape. Each computer processor that was manufactured understood a certain set of instructions, which were represented by numbers. Here's an example:

0000000100000EF0: 55 48 89 E5 48 83 EC 10 48 8D 05 51 00 00 00 48
0000000100000F00: 89 C7 E8 1D 00 00 00 C7 45 F8 01 00 00 00 8B 45
0000000100000F10: F8 89 45 FC 8B 45 FC 48 83 C4 10 5D C3 90 FF 25
0000000100000F20: 14 01 00 00 FF 25 16 01 00 00 00 00 4C 8D 1D FD
0000000100000F30: 00 00 00 41 53 FF 25 ED 00 00 00 90 68 00 00 00
0000000100000F40: 00 E9 E6 FF FF FF 68 0C 00 00 00 E9 DC FF FF FF
0000000100000F50: 68 65 6C 6C 6F 2C 20 77 6F 72 6C 64 00 01 00 00

This sucked.

Assembly Language

Early on people realized that writing the machine code directly was boring and error prone, so they developed "Assembly Languages", a way of writing computer operation sequences (programs) that were easier to read and understand by humans.

These programs were then "compiled" into machine code so that they could be run by the processors.

0000000100000EF0: push   rbp
0000000100000EF1: mov    rbp,rsp
0000000100000EF4: sub    rsp,0x10
0000000100000EF8: lea    rax,[rip+0x51]                 ;"hello, world"
0000000100000EFF: mov    rdi,rax
0000000100000F02: call   0x100000f24 <dyld_stub_puts>
0000000100000F07: mov    DWORD PTR [rbp-0x8],0x1
0000000100000F0E: mov    eax,DWORD PTR [rbp-0x8]
0000000100000F11: mov    DWORD PTR [rbp-0x4],eax
0000000100000F14: mov    eax,DWORD PTR [rbp-0x4]
0000000100000F17: add    rsp,0x10
0000000100000F1B: pop    rbp
0000000100000F1C: ret

This still sucked.

Programming Languages

The ideas behind modern programming languages were developed during the 1960s and early 1970s, giving us languages similar to human speech for writing computer programs.

var number_of_cookies = 20;
var number_of_people = 30;

if ( number_of_cookies < number_of_people ) {
  log( 'Not enough cookies!' );
} else {
  log( 'Nom nom nom.' );
}

Hooray!

Types of Programming Languages

Over time, programming languages have evolved into two distinct groups: compiled and interpreted.

Compiled Languages

Compiled programming languages are converted directly into machine code before they are run. Some examples: Assembly, C, C++.

Interpreted Languages

Interpreted programming languages are converted into machine instructions "on-the-fly" by another program (called an "interpreter"). Common examples: Ruby, PHP, and our favorite for this class, JavaScript.

Scripting Languages

In addition, some "interpreted languages" are specially tailored not just for being interpreted into machine code, but for automating parts of another program (i.e. giving them a "script" to follow). Javascript originally fell into this category.

Why JavaScript

  • It is the most ubiquitous programming language in the world.
  • It is the standard for interactive development on the web.
  • It is very approachable and relatively easy to learn.
  • It's going to help you get a job.

Usage

JavaScript is increasingly being used to perform different types of tasks including program automation, browser extension authoring, building desktop applications, and server-side programming.

However, by far the most common use of JavaScript is to add interactivity to web pages, so that is what we will focus on for this class.

Hello World

Everyones favorite first program

var message = "hello, world";

// Displays hello, world on the screen
log(message);

Statements

Javascript programs consist of a sequence of "statements", each of which describes some sort of operation that the computer should perform.

Statments (usually) end with a semi-colon.

Although it isn't required, statements should each be on their own line for readability's sake.

var message = "hello, world";
log(message);

Comments

Comments don't actually do anything, they're just a way of leaving notes for yourself (or whoever else may be reading your program) in the code.

Javascript has two different types of comments: single line, and multi-line.

Single-line comments

// This is "single line" comment. It ignores everything until the end of the line.

Multi-line comments

/* 
This is a "multiple line" comment. It ignores everything until 
the next asterisk-slash combination.

These are also called C-style comments.
*/

Data Types

Primitive Data Types

The three basic data types in Javascript are:

  • numbers
  • strings
  • booleans

These three data types are called "primitive" data types.

Functions and Objects

In addition to the primitive data types, Javascript has two other data types: functions and objects. Sometimes these are called "composite" or "complex" data types.

Data Types: Numbers

  • In JavaScript, there is one "number" datatype for all numeric values. This is different from most programming languages where there is one type for "whole numbers" (called Integer), and one type for numbers with a decimal point (called Float, or floating point)
  • Javascript supports positive and negative numbers, with or without decimal points, and even the numbers infinity and negative infinity.

Examples

0
123
3.14
.3333333
5e10
1.5e-10
-27.1
Infinity
-Infinity
0xF3
0377
NaN

The last one up there, NaN, is a special number that means "Not a Number". More on that later.

Data Types: Strings

  • A String is a series of characters
  • Strings are defined by surrounding zero or more characters with single or double quotes. The type of quote doesn't matter, but the ending quote must match the starting one.
  • The "escape character", backslash, can be used to add characters to a string that are not normally allowed.
  • Characters that need escaping are ", ', \
  • You can include single quotes in a double quoted string and double quotes in a single quoted string without escaping them
  • to create a new line use: \n
  • to create a tab use: \t
  • to create a unicode character use: \uFFFF (where FFFF is the unicode sequence)

.

log("Strings are \"important\".");

Data Types: String Examples

log("hello");
log("Tim said, 'hello'");
log("I am a line\nI am a line too");

log("\t\ttwo tabs for me");
log(""); //empty string
log("\u00BFQue pasa?");

Data Types: Booleans

  • A boolean is a value that is either true or false.

.

log( true );
log( false );

Data Types: Functions

Functions store a series of operations together so that they can be run over and over again. We'll cover functions more in a few weeks.

function squared( num ) {
  return num * num;
}

log( squared(3) )
log( squared(5) )

Right now, the important thing is that you can "call" a function by adding parenthesis after it's name, optionally including any values that the function needs inside of the parenthesis.

Data Types: Objects

Finally, Javascript has one more data type: objects. Objects are simply compilations of primitives and functions. We'll talk more about objects in a few weeks as well.

log( Math.sqrt(9) )
log( Math.sqrt(25) )

Right now the important thing is that you can access the primitive values and functions by adding a period and the related data value or method's name after the name of the object.

Operations

But data types aren't really any use until we do something with them. JavaScript has a whole slew of "operations" that can be performed on data.

Operations: Math

One of the main ways of telling the computer to do something is through operators. Some of the most basic operators do simple arithmatic.

log(5 + 5); //add
log(10 / 2); //divide
log(52 % 10); //modulos
log(5 * 5); //multiply

The precedence of the operators is just like you learned in math class.

  • parentheses first
  • mutliplication, division, modulos
  • add, subtract
  • then go left to right

Operations: Math

What does this print?

log( 11 % 3 + 3 * 2 - 8 + (12 * 1) );

Operations: Concatenation

The + operator has another meaning when it is used in between strings. It joins the two strings together into a single string. This is called concatenation.

log('hello' + ', ' + 'world');
log('5' + 55);

Note above that because the first value is a string, concatenation is performed instead of addition (the other value is converted to a string, and then the two values are joined together).

Variables

Think of variables as containers to hold your data. You can store data into variables using the assignment operator (=).

var name;   // This is call "declaring" the variable.
name = "Jon";
name = "Tim";

// You can also assign a value to a variable at the same time you declare it.
var name2 = "Sarah";
  • You only need to declare a variable once.
  • If you don't declare your variables BAD THINGS WILL HAPPEN.

Variables: Usage

You can substitute variables anywhere that you would normally use the actual data value.

var tomsAge = 25;
var toddsAge = 30;
log( tomsAge + toddsAge );

tomsAge = 35;
log( tomsAge + toddsAge );

// Our arithmatic example from earlier.
var part1 = 11 % 3 + 3 * 2 - 8;
var part2 = 12 * 1;
log( part1 + part2 );

Variables: Identifiers

An "identifier" is a fancy word for the variable's name.

  • Identifiers are case sensitive
  • Must begin with a letter, underscore, or dollar sign
  • After the first character there can be digits, letters, underscores and dollar signs
  • You cannot use reserved words as identifiers. These include:

abstract, boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, export, extends, false, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, super, which, synchronized, this, throw, throws, transient, true, try, typeof, var, volatile, void, while, with

You will also want to avoid functions and attributes of the window object (more on the window object later). These are global variables and you can override them by declaring your own.

Variables: Valid Identifier Examples

var name;
var Name;
var firstName;
var first_name;
var _first_name;
var D20;
var $element;
var _;
var $;
var MAX_VALUE;

Note that just because an identifier is valid doesn't mean that it's a good one to use.

Variables: Invalid Identifier Examples

var 1234;
var #abc;
var &two;
var hello-world;
var two&two;
var class;
var default;
var final;
var package;
var no-dashes-allowed;

Variables: Operators For Variables

var x = 5;
var y = 3;
x += 4;    // x = x + 4;
x -= 2;    // x = x - 2;
y *= x     // y = y * x;
x *= 3;    // x = x * 3;
x /= 7;    // x = x / 7;
x %= 3;    // x = x % 3;
x++;       // x += 1;
y--;       // y -= 1;

/* And also these, which you will not see again in this class. */
++x;       // x += 1;
--y;       // y -= 1;

log("x: " + x);
log("y: " + y);

Variables: typeof

In JavaScript, (unlike many other progamming languages), any data value type can be assigned to any variables. This is called "loosly typed". The current data type of a variable can be determined using the typeof keyword.

var x = 4;

log( typeof x );

x = 'Test';

log( typeof x );

x = '5';

log( typeof x );

var y;
log( typeof y );

Variables: undefined and null

As illustrated on the previous slide, if a variable hasn't had a value assigned to it yet, the typeof keyword returns a special data type called "undefined".

However, if you want to explicitly set a variable to "nothing", instead of setting it to undefined, programmers (by convention) set the variable to a special object called "null".

var x;
x = 4;

log( typeof x );

x = null;

log( typeof x );
log( x );

Common Programming Scenarios

Showing Information

alert()

The easiest (and ugliest) way to show something to the person viewing your web page is by using alert().

alert("Hi there. I'm annoying.");

Later on in the class, we'll add HTML to the web page and change parts of the web page directly.

console.log()

There's also a way of leaving notes that aren't visible on the actual web page, but show up in the special "console" area of your web browser.

console.log("This is a great place to check values if you're stuck.");

User Input

The easiest (and ugliest) way to get a value from the person viewing your web page is by using prompt().

var answer = prompt('What is your name?');
log(answer);

Later on in the class, we'll use forms to get values from the user. They can actually be (somewhat) styled.

Note that whatever the user types in is always given back to you as a STRING...

Converting Strings to Numbers

  • It is a very common task to convert a string into a Number in JavaScript, because all input that can be given by a user is presented as a string in JavaScript
  • You can use parseInt() if you need an integer
  • You can use parseFloat() if you need to retain the decimal

parseInt

  • When converting strings to integers you can use a global function called parseInt()
  • parseInt takes two arguments: the string to parse and a radix.
  • the radix is optional but should be used to avoid a hexadecimal or octal interpretation
  • If the string passed to parseInt does not begin with a digit or - then NaN is returned
  • parsing of the integer stops if a non digit is encountered but the number so far is returned. This means parseInt cannot be used to determine if a string is an integer. It also means that decimals are truncated.

.

log( "100" + 10 );
log( parseInt("100", 10) + 10 );
log( parseInt("3.75" ,10) );
log( parseInt("-27", 10) );

log( parseInt("999hello", 10) );
log( parseInt("kitty", 10) );

// Danger!
log( parseInt("0890") );
log( parseInt("0890", 10) );

parseFloat

  • parseFloat is another global function that converts strings to numbers
  • as you might gather from its name it parses floats.
  • parseFloat takes one argument: the string to be parsed

.

log("3.14159" + 2);
log(parseFloat("3.14159") + 2);

Math

Javascript provides us with a global Math object that has several useful methods.

Here are a few of them

var num = 2.5;
var x = -3;
var y = 2;
var z = 4;

log( Math.abs(x) );     // absolute value
log( Math.ceil(num) );  // ceiling.. rounds up
log( Math.floor(num) ); // rounds down
log( Math.round(num) ); // "normal" round
log( Math.pow(x,y) );   // power... x^y
log( Math.random() );   // random number between 0 and 1.
log( Math.sqrt(z) );    // square root
log( Math.max(x,y) );   // largest number
log( Math.min(x,y) );   // smallest number
log( Math.PI );         // PI

There's a full list here. We'll use some of these methods in this week's homework, and more next week.

Doing something every X seconds.

We'll talk about this more after we know how to write our own functions.

If you're really curious, check out these functions:

Final Notes

Whitespace

  • In JavaScript whitespace (spaces, tabs, and newlines) are not significant.
  • Whitespace is used to make code more readable to humans.
  • Tabs are usually applied to the beginning of expressions inside of blocks ({ })
  • Newlines are usually used after expressions
  • Spaces are also used in various places to give visual seperation

Check your code with JS Beautifier.