JavaScript Fundamentals
Client-Server Model
- Distributed System
- Clients make request
- Servers fulfill request
Word Processors
Client-Server Lite
Word Document
file1.docx
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cp:coreProperties
xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:dcterms="http://purl.org/dc/terms/"
xmlns:dcmitype="http://purl.org/dc/dcmitype/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<dc:creator>User 1</dc:creator>
<cp:lastModifiedBy>User 2</cp:lastModifiedBy>
<cp:revision>3</cp:revision>
<dcterms:created xsi:type="dcterms:W3CDTF">2012-11-07T23:29:00Z</dcterms:created>
<dcterms:modified xsi:type="dcterms:W3CDTF">2013-08-25T22:18:00Z</dcterms:modified>
</cp:coreProperties>
Open Document
file1.docx
Operating System (Server)
Word Processor (Client)
requests file1.docx
loads file from drive
sends contents of file1.docx
Display Document
file1.docx
renders
Browsers and the Internet
Client-Server
Differences
- Files can be on a remote computer, anywhere in the world
- Main file doesn't always contain everything it needs to render. Needs to load additional files.
- All files don't finish loading at the same time.
Uniform Resource Locators (URLs)
http://example.com/index.html
Protocol
Domain Name
File
Request HTML
Yipeeeee, the cloud!
index.html
Internet
Remote Computer (Server)
http://example.com/index.html
Load HTML
index.html
<img src="http://example.com/image1.png" />
<link href="http://example.com/styles.css"></link>
image1.png
styles.css
Render HTML
Important
- Size matters!
- Order matters!
- By default, JavaScript blocks
The <script> tag
<!-- A script tag can reference files on a different computer using a domain name -->
<script src="http://example.com/scripts.js"></script>
<!-- If it's a local script, there no need to include the full domain -->
<script src="scripts.js"></script>
"Prevent" Script Blocking - Traditional
<html>
<head>
<!-- ... -->
</head>
<body>
<!-- ... -->
<!-- Place script tags right before closing BODY tag -->
<script src="http://example.com/scripts.js"></script>
<script src="scripts.js"></script>
</body>
</html>
Prevent Script Blocking - HTML5
<html>
<head>
<!-- ... -->
<script async src="http://example.com/scripts.js"></script>
<script async src="scripts.js"></script>
</head>
<body>
<!-- ... -->
</body>
</html>
<html>
<head>
<!-- ... -->
<script defer src="http://example.com/scripts.js"></script>
<script defer src="scripts.js"></script>
</head>
<body>
<!-- ... -->
</body>
</html>
HTML & CSS
HTML
CSS
JavaScript, FTW
Document Object Model (DOM)
window
window.document
Variables
// We DECLARE variables using the keyword var, followed by the name of the variable.
var x;
// We ASSIGN a value to a variable using the equals sign, =
x = 5;
// We can DECLARE and ASSIGN on the same line
var y = 10;
// We can assign the value from one variable to another
x = y; // x is now 10
// We can store things other than numbers of course
var lastName = "Stark"; // This is called a String
var firstName = 'Jared'; // Strings are contained in either single or double quotes
// We can also store Boolean values, which represent true or false
var isGameHost = true;
// Some special values in JavaScript
var vehicle = undefined;
var currentWeapon = null;
var average = 20 / "boo"; // NaN - Not a Number
Statements and Expressions
var five = 5; // This is an expression that evaluates to 5
// and is assigned to the variable 'five'
var ten = five + 5; // This expression evaluates to 10 and
//is assigned to the variable 'ten'
(10 * 10); // This is an expression that evaluates to 100,
//and does nothing with the result
Comparison Operators
// We can compare numbers
var x = 5;
var y = 10;
(x == y); // false
(x > y); // false
(x < y); // true
(x <= y); // true
(x >= y); // false
(x != y); // true
// We can also compare Boolean
var isLoggedIn = true;
(isLoggedIn == true); // true
(isLoggedIn == false); // false
(isLoggedIn != true); // false
(isLoggedIn != false); // true
// We can compare Strings
("Jared" == "Jared"); // true
("Jared" != "Jared"); // false
== vs ===
// What happens when we compare strings and numbers?
("Jared" == 10); // false
// What if the string looks like a number?
("10" == 10); // true?
// Always use === & !==
("10" === 10); // false
("10" !== 10); // true
false vs "falsy"
// The following values are always considered false
(0 == false); // true
('' == false); // true
(undefined == false); // true
(null == false); // true
(false == false); // true
(NaN == false); // true
(10 == true); // true
('jared' == true); // true
(true == true); // true
if statement
var isLoggedIn = true;
if (isLoggedIn == true) {
// Show username
} else {
// Show Login button
}
// Same as above
if (isLoggedIn) {
// Show username
} else {
// Show Login button
}
// Works with any expression that evaluates to "truthy" or "falsy"
if ("Jared") {
// This would execute since "Jared" == true
}
if (0) {
// This won't execute since 0 == false
}
Keep it DRY
var name1 = 'jared';
name1 = name1[0].toUpperCase() + name1.slice(1); // 'Jared'
var name2 = 'john';
name2 = name2[0].toUpperCase() + name2.slice(1); // 'John'
var name3 = 'sarah';
name3 = name2[0].toUpperCase() + name2.slice(1); // 'John'???
function declaration
function capitalizeName() {
name1 = name1[0].toUpperCase() + name1.slice(1);
}
function parameters
function capitalizeName(name) {
name = name[0].toUpperCase() + name.slice(1);
}
returning a value
function capitalizeName(name) {
name = name[0].toUpperCase() + name.slice(1);
return name;
}
function invocation
function capitalizeName(name) {
name = name[0].toUpperCase() + name.slice(1);
return name;
}
capitalizeName('jared');
invocation is an expression
function capitalizeName(name) {
name = name[0].toUpperCase() + name.slice(1);
return name;
}
var name1 = capitalizeName('jared');
Practice
Scope
Visibility
John
Dan
Sarah
Brian
Jill
Can See:
John
Can See:
John
Dan
Can See:
John
Dan
Sarah
Can See:
John
Dan
Sarah
Brian
Functions create Scope
var name = 'jared';
function capitalizeName() {
name = 'Jared'; // name is visible because it's in a parent scope
return name;
}
var name1 = capitalizeName(); // name1 is 'Jared'
Local scope
function doSomething() {
var num1 = 10; // num1 is "local" to function
}
var num2 = num1; // num2 is undefined
Hide vars in Parent Scope
var fruit = 'apple';
function makePie() {
var fruit = 'strawberry'; // Is a new variable local to makePie. Hides outer variable
}
makePie();
(fruit == 'apple'); // true
functions inside of functions
function outer () {
var num1 = 5;
function inner() {
var num2 = 10;
(num1 + num2); // 15, num1 is in parent scope and accessible
}
function inner2() {
var num3 = 20;
(num2 + num3); // NaN - num2 is NOT in parent scope
}
(num1 + num2); // NaN - num2 is local to inner and not accessible
}
(num1 + num2); // NaN - num1 and num2 are not accessible
Nested function example
function capitalizeName(name) {
function capitalizeFirstLetter() {
var firstLetter = name[0].toUpperCase(); // Name is visible because
// parameter is in parent scope
return firstLetter;
}
name = capitalizeFirstLetter() + name.slice(1);
return name;
}
var name1 = capitalizeName('jared');
Parameters are local to Function
function capitalizeName(name) {
function capitalizeFirstLetter() {
var firstLetter = name[0].toUpperCase(); // Name is visible because
// parameter is in parent scope
return firstLetter;
}
name = capitalizeFirstLetter(name) + name.slice(1);
return name;
}
var name1 = name; // undefined; name is parameter to capitalizeName function
Parameters are local to Function
function capitalizeName(name) {
var name = 'Bob';
function capitalizeFirstLetter() {
var firstLetter = name[0].toUpperCase(); // Name is visible because
// parameter is in parent scope
return firstLetter;
}
name = capitalizeFirstLetter(name) + name.slice(1);
return name;
}
var name1 = capitalizeName('Jared'); // name1 is 'Bob'
Parameters are local to Function
function capitalizeName(name) {
function capitalizeFirstLetter(name) {
name = 'Bob';
var firstLetter = name[0].toUpperCase(); // Name is visible because
// parameter is in parent scope
return firstLetter;
}
name = capitalizeFirstLetter(name) + name.slice(1);
return name;
}
var name1 = capitalizeName('Jared'); // name1 is 'Bared'
Beware global variables
name = 'Jared';
(window.name === name); // true
function evil() {
title = 'Mwahahahaa';
}
evil();
(window.title === title); // true (This is the browser window title)
Example
// yourScript.js
function setLanguage(language) {
if (language === 'javascript') {
alert('woot!');
} else {
alert('boo');
}
}
// myScript.js
function setLanguage(language) {
if (language === 'spanish') {
alert('Hola');
} else if (language === 'french') {
alert('Bonjour');
} else {
alert('Hi');
}
}
// In your HTML file...
//<script src="yourScript.js"></script>
//<script src="myScript.js"></script>
setLanguage('javascript'); // ???
Returning Functions from Functions
function outer() {
return 5;
}
outer; // A variable. Value is a function
outer(); // An expression that invokes function outer
// The value produced is 5;
function outer() {
function inner() {
return 10;
}
return inner; // Doesn't invoke, just returns the variable inner
}
inner; // undefined because declared inside function outer
outer; // A variable. Value is a function
var x = outer(); // An expression that invokes function outer
// The value of x is just another function (inner)
x; // A variable. Value is a function
x(); // Because the value of x is a function, we
// can invoke it.
var y = x(); // The value produced is the return value of function inner
(y === 10); // true
Practice
Function Declaration vs Expression
function setLanguage() {
// Do something
}
var addNumbers = function addNumbers(num1, num2) {
// add numbers
};
// The right side of the = is an expression, the value it produces
// is a function
var addNumbers = function (num1, num) {
// add numbers
};
// BAD: Can't declare an anonymous function
function () {
}
// We can update our outer function from the previous example to just
// return an anonyous function
function outer(name) {
return function() {
return name;
}
}
var inner = outer('Jared') // same as before
Callbacks
function sayHi(){
console.log("Hi");
}
// A callback is a pattern of giving a function another function to invoke
function invokeThisForMe(fn2){
fn2();
}
invokeThisForMe(sayHi); // Pass our first function into a function so we can function while you function
// Asynchronous - Not in order, 2 things at the same time.
function invokeThisForMeLater(fn2){
setTimeout(fn2, 3000)
}
invokeThisForMeLater(sayHi);
//Repeatable operations
var nums = [1,5,9];
//call this function for every item in the array
function changeAll(array, fn){
for(var i = 0; i < array.length; i++){
array[i] = fn(array[i])
}
}
doForAll(nums, function(num) { return num + 3 } );
doForAll(nums, function(num) { return num - 4 } );
doForAll(nums, function(num) { return num * 8 } );
doForAll(nums, function(num) { return num / 2 } );
Practice
JavaScript Fundamentals
By Jeremy Robertson
JavaScript Fundamentals
- 1,995