var message = "hello, world";
log(message);
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.
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.
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.
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!
Over time, programming languages have evolved into two distinct groups: compiled and interpreted.
Compiled programming languages are converted directly into machine code before they are run. Some examples: Assembly, C, C++.
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.
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.
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.
var message = "hello, world";
// Displays hello, world on the screen
log(message);
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 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.
// This is "single line" comment. It ignores everything until the end of the line.
/*
This is a "multiple line" comment. It ignores everything until
the next asterisk-slash combination.
These are also called C-style comments.
*/
The three basic data types in Javascript are:
These three data types are called "primitive" data types.
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.
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.
.
log("Strings are \"important\".");
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?");
.
log( true );
log( false );
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.
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.
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.
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.
What does this print?
log( 11 % 3 + 3 * 2 - 8 + (12 * 1) );
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).
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 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 );
An "identifier" is a fancy word for the variable's name.
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.
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.
var 1234;
var #abc;
var &two;
var hello-world;
var two&two;
var class;
var default;
var final;
var package;
var no-dashes-allowed;
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);
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 );
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 );
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.
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.");
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...
parseInt()
if you need an integerparseFloat()
if you need to retain the decimalparseInt()
NaN
is returned.
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) );
.
log("3.14159" + 2);
log(parseFloat("3.14159") + 2);
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.
We'll talk about this more after we know how to write our own functions.
If you're really curious, check out these functions:
Check your code with JS Beautifier.
Table of Contents | t |
---|---|
Exposé | ESC |
Presenter View | p |
Source Files | s |
Slide Numbers | n |
Notes | 2 |
Help | h |