Afghanistan
Albania
Algeria
Andorra
Anguilla
Antigua & Barbuda
Argentina
Armenia
Aruba
Australia
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belgium
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire
Bosnia & Herzegovina
Botswana
Brazil
British Indian Ocean Ter
Brunei
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Canada
Canary Islands
Cape Verde
Cayman Islands
Central African Republic
Chad
Channel Islands
Chile
China
Christmas Island
Cocos Island
Colombia
Comoros
Congo
Cook Islands
Costa Rica
Cote D Ivoire
Croatia
Cuba
Curacao
Cyprus
Czech Republic
Denmark
Djibouti
Dominica
Dominican Republic
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Ter
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guinea
Guyana
Haiti
Hawaii
Honduras
Hong Kong
Hungary
Iceland
India
Indonesia
Iran
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Japan
Jordan
Kazakhstan
Kenya
Kiribati
Korea North
Korea South
Kuwait
Kyrgyzstan
Laos
Latvia
Lebanon
Lesotho
Liberia
Libya
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mexico
Midway Islands
Moldova
Monaco
Mongolia
Montserrat
Morocco
Mozambique
Myanmar
Nambia
Nauru
Nepal
Netherland Antilles
Netherlands (Holland, Europe)
Nevis
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Norway
Oman
Pakistan
Palau Island
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn Island
Poland
Portugal
Puerto Rico
Qatar
Republic of Montenegro
Reunion
Romania
Russia
Rwanda
Saipan
Samoa
Samoa American
San Marino
Sao Tome & Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Singapore
Slovakia
Slovenia
Solomon Islands
Somalia
South Africa
Spain
Sri Lanka
St Barthelemy
St Eustatius
St Helena
St Kitts-Nevis
St Lucia
St Maarten
St Pierre & Miquelon
St Vincent & Grenadines
Sudan
Suriname
Swaziland
Sweden
Switzerland
Syria
Tahiti
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad & Tobago
Tunisia
Turkey
Turkmenistan
Turks & Caicos Is
Tuvalu
Uganda
Ukraine
United Arab Emirates
United Kingdom
United States of America
Uruguay
Uzbekistan
Vanuatu
Vatican City State
Venezuela
Vietnam
Virgin Islands (Brit)
Virgin Islands (USA)
Wake Island
Wallis & Futana Is
Yemen
Zaire
Zambia
Zimbabwe
Reading Assignment
4.) What is JavaScript?
3.) Why Language Matters
2.) On Programming
1.) Introduction
Eloquent JavaScript
Introduction
"Personal" Computers came with BASIC
Interaction w/ computer REQUIRED BASIC
1970's
Transitioning to programming was easy.
Tinkering was natural
Now computer interfaces are all GUI's
Can just point w/ a mouse rather than use a language.
Now have to actively seek out a programming environment
Languages have evolved.
More complex than BASIC
But programming still runs compters under the hood.
Every web browser runs JavaScript
On Programming
Programs easily become salad.
Fundamental rules are simple and clear
Programming be the hard.
Also here to learn basic principles of programming
"Confucius is an ass."
Programs begin defining their own rules.
Programming becomes art.
Can't just read.
Need to actively get at learning this.
"There's no limit to complexity of programs."
A program is
Done well it runs w/o crashing
A piece of text typed by a programmer
Directing force that makes the computer do what it does.
A machine with intermeshed gears
A computer is a machine that hosts programs.
Computers are stupid--but fast.
Programming is a game
A program is a building of thought
Programs cost nothing to build.
Just takes typing.
Careless programming can make messes easily.
Programming is controlling complexity.
Great programs are simple, subdued.
"Best Practices" help manage complexity.
Just like every other design rules: break when you have reasons to do so.
Programming space is infinite, and mostly unexplored.
Programmers who refuse to keep exploring will stagnate
Stagnation leads to management.
Why language matters
Assembly adds simple commands.
Languages are built as layers of abstraction.
Pseudocode is one step down from Engrish.
Matlab adds a library of simple functions
JavaScript is the "Engrish" of programming: absorbed bits of everything.
Fortran adds named memory contsructs
Stonehenge was programmed in raw binary.
What is JavaScript?
Language used on web pages
Runs server-side on node.js
"ridiculously liberal"
Supposed to be beginner-friendly
But problems are difficult to find.
Allows flexibility of paradigms.
Nothing to do with Java.
Really more "ECMAScript" per the standard.
General-purpose language
No requirement to run inside a web browser.
ECMAScript 3 is the LCD.
Everything beyond ECMAScript 3 is back-compatible.
Questions
Comment on complexity in programming
Why programming laguages?
Java vs. JavaScript
ECMAScript vs. JavaScript?
Programs should be simple
What is a program?
Build complexity through abstraction.
An abstract machine.
Directing initiative to a computer.
Text typed by a programmer.
Need to manage complexity with tools such as "best practices"
Need rungs on the abstract ladder between "machine" and "human"
Provide frameworks for problem solving
Obnoxious C++ hack.
Browser programming language.
Standard Specification
Ad-hoc implementations.
JavaScript Introduction
How HTML is used
What HTML is
How web development is
Interact with the user
JavaScript
How you should be thinking vs. new problems
Getting an understanding of
Get on Google
Find solutions
Our website is boring.
Web 2.0
Web 1.0
Static
Not a lot of interaction.
Structure of a website
Add logic
Intro to programming
HTML is not "programming"
Just defining layout and design.
Alert demo
Remove everything except title.
Add some logic.
Cannot embedd HTML in JavaScript
JavaScript is a different language
<script> JavaScript </script>
Can embed JavaScript in HTML
End lines with ;
New syntax: code.
JS is 100% integrated w/ HTML
All browsers support JS
Can't do this trick with C/C++ etc.
Console Reading Assignment
Understanding other Dev Tools
Working with an HTML file
Working in the console
Working with the Console in a Browser
Introduction
Conclusion
How 2 Use the JS Dev Console
FireFox
Chrome/Brave
DOM Document Object Model
Network
Responsive Design
Working w/ a JS console w/i a Browser
Other JS Dev Tools
data types
JQuerry
D3.js
Inspect the DOM
Debugger
Network Analysis
Log information
Interact with WebPage via JS expressions w/i page's context.
Write
Monitor
It's a terminal right in your browser!
= -> Developer -> Web Console
<ctrl><shft>K
<...> -> More Tools -> Developer Tools
<cntrl><shft>J
>> alert("Hello, World!");
<- undefined
console.log("Hello, World!");
Hello World!
>> let d = new Date();
>> console.log("Today's date is " + d);
<- Today's date is Fri Feb 15 2019 14:33:53 GMT-0800 (Pacific Standard Time)
Up arrow recalls history
Can get/set tags in the enclosing HTML file.
Browser creates DOM on loading.
>> document.body.innerHTML = "<h1> Today's date is " + d + "</h1>"
>> document.body.style.backgroundColor = "lightblue";
>> document.body.style.color = "white";
DOM is a tree of objects
Shows HTML elements in heiarchial view.
Inspector (FireFox)
Can be visualized
Elements in Chrome|Brave
CSS is a side-panel w/i DOM
Network tab logs network actions and performance.
Works during live debugs.
Chrome|Brave Network docs
FireFox docs
FireFox's Responsive Design Mode
Chrome|Brave's Device Mode
React correctly across devices.
Questions
Displays function output back to the console.
Hack a page w/ console.
What does console.log do?
Pull console up in Chrome|Brave
What is console good for?
Investigating values
Issuing JS commands
Modifying displayed values
<...> -> More Tools -> Developer Tools
<cntrl><shft>J
>> document.body.innerHTML = "<h1> Today's date is " + d + "</h1>"
Chrome Console
For playing around
For learning
For trying things out.
<right-click> Inspect -> console tab
But can also execute JS in console.
For testing
Browsers execute JS on loading pages.
Executes code in the web page context
Talking directly to the JS engine
Trying programs
use document.write to affect HTML code directly.
Enter in a dummy .html file
Book website
Reading Assignment: Chapter 1
Variables
Control Flow
Values
Quiz
What is binary data?
A sequence of bits
What are values?
Chunks of binary data
What kind of data do computers understand at the lowest level?
Binary
What are some types of values?
Numbers
Text
Functions
NaN
Infinity and -Infinity
What kinds of special numbers do you know in JavaScript?
18
(4 + 5)*2
2
(10 + 22)%3
Values
Boolian, Comparison, and Logic
Unary Operators
Strings
Arithmetic
Numbers
Expressions and Statements
All data is binary. Everything else is an abstraction
Every value has a type.
Values cost nothing to create
Concurrent Value population size is limited by memory.
Unused values are "garbage collected"
All numbers are 64-bit.
Operators enable arithmetic.
Unary: -, sqrt()
Binary: +,-,*,/,%,!
Order of operations applies.
(parenthesis force operation order)
"Array of characters enclosed by quotes"
'Single' or "Double" quotes work, but only as pairs.
\ escapes
\n, \t, \', \", \\
'Concatinates' + 'strings.'
true || false
typeof, -, sqrt()
Enables comparison operators.
Expressions produce values.
<, >, ==, !=, <=, >=
Works on strings alphabetically per Unicodes
Statements are expressions.
Statements affect execution scope
Statement;
Statements create side effects.
Variables
Rememeber: functions are values.
Are persistent within scope.
Reserved Words
Keywords
A named value.
Names can be any continuous string
No whitespace
Cannot start with a digit.
= associates values to names.
All variables are pointers to values.
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 switch synchronized this throw throws transient true try typeof var
The Environment
Functions
prompt and confirm
print( )
Modifying the Environment
Variables
container of scope.
code as a value
invoke via name w/ (parenthesis)
String value w/i (parenthesis) is passed to the code
Useful for the side effects they produce.
Can produce and return a value.
Return values may embed in expressions.
confirm
prompt
"OK"/"Cancel" -> true | false
"requests a string"
Included in JS
Sends text output..."somewhere".
All values are mutable.
Some values are functions.
Dangerous to redefine terms.
Program Structure
while and do Loops
Conditional Execution
Breaking out of a Loop
for Loops
Execution is top-to-bottom, unless told otherwise.
Number( ) converts strings to numbers.
if ( condition ) { positive body } else { negative body }
NaN enables isNaN( ) checks.
while ( condition) { body }
Uses iterator values to track progress.
{ block delimiters }
do { body } while (condition)
for ( var initialize; check limit; update) { body }
break; kicks out of closest loop.
; // empty statement
Beware the break; statements.
Typographical Style
Comments
Dispatching on a Value with switch ( )
Capitalization
Indenting Code
Updating Variables Succinctly
useCamelCase
// one-liners
var++, var--
+=, -=, *=, /=
spaces or tabs. don't mix.
Indent control structures.
switch ( value ) { case1 <blah1>: body1 break; case <blah2>: body2 break; default: default body break;}
/* going on about it */
Use judiciously.
More on Types
JS for "pointer to void".
More on && and ||
Dangers of Automatic Type Conversion
Automatic Type Conversion
Undefined Values
var something; // no value
Subtlties
"subroutines" (Fortran definition) return 'undefined'.
null == undefined
null: defined, but no value.
JS will always coerce type.
===, !== force type comparisons.
String <-> Number expressions.
Often create NaN's.
NaN is the dominant type.
true || other value
false && other value
Variables in JS
Can have different kinds of variables
Can change the value in the future
Gives us flexibility
Define variable
Other events happen
Want to change the variable in the middle of execution.
Placeholder for a value
functions etc.
Number
String
Supports operators
Order of operations matters.
Simple Programer Course
Setup
Big Words and JS
Understanding Frameworks and the Wierd Parts
Simple Programmer Courses
JavaScript
Introduction and goal
Getting Started
Tony Alesea
Goals
About JS as a programming language
Not about making a webpage interactive in JQuery
Not about the in and outs of NodeJS
How JS works under the hood
Delve into advanced concepts
Understand things people who built JS understand
Make you a better programmer
Intro to JS
Understanding JS at the princples level
JS Falsely looks like other languages.
Mindset
Paradigm
Advanced JS does not seem wierd.
JS is nothing like Java, C/C++, or C#.
JS is a different
Concept
How JS works
Why JS works the way it does.
JS is deceptively
Powerful
Beautiful
Philosophy of Learning Code
Understand.
But parroting code only takes you so far.
Examples are important.
Providing code to imitate
Designing programming courses.
Biggest mistake
Don't imitate
Will crash in real world
If deeply understand
Be able to debug hard problems
Come up with interesting new solutions
JS is just a tool
What the tool is doing for you.
Appreciate good code.
Borrow from it
Enhance it.
Will look at plenty of examples
But will look at principles first.
Enable real-world understanding.
Prerequisites
What a JS file is
Variables
Functions
Loops
A beginning programmer skillset.
Basic JS understanding
Setup
Brave
Atom
GitHub
Notepad++
Text Editor
Browser with Dev tools
Need 2 Things:
IE/Edge
Safari
Chrome
MS Code
Brackets
FireFox
Course uses
Comes with a built-in server
File -> Open Folder
Folder contains code
Can adjust themes
Big Word Alerts
Will give more detail
Will give definition
Will take "Big Word Alert" for simple content
Its just vocabulary
Will show applications
Will discuss in depth
In CS words are bigger than concepts.
Understanding
Fundamental, foundational knowlege
Going beyond the basics
Need to understand how it works
Is abstracting away the server, computer, etc.
Will see applications soon enough.
Generates "ah-ha" moments.
JS the programming langauge
Frameworks
However bad place to start learning
AngularJS
Libraries
Developed
Frameworks
JQuery
Open source community
Just JS code.
Great for rapid building neat applications
Good example code.
Can't read JS code
Dangerous not to understand JS.
Learn to read framework code.
Build our own mini-framework.
The Wierd Parts
No programming language is perfect.
Here to understand the hows and why's.
May be some of the most powerful features of JS
Different parts look wierd.
Will point out JS pitfalls.
Expectations set by other langauages.
Syntax Parser
Compilers
Someone else wrote a program to translate it for the computer
Your code isn't magic
Validates grammar
Determines what it does
Reads your code
A program that
Interpreter
Character - by - character
Your Code
Computer Instructions
Parser
Extra Stuff
Intermediate program that's re-creating your code
Execution Contexts
And beyond
Can contain
Your code
Code that is running
Help manage
A wrapper
Lexical Environments
Syntax
Vocablulary
Where you write something is important.
Within the code you write
Something sits physically
Grammar.
Where
Locations approximate machine code.
Makes decisions
Switches
Important foundation
Name-Value Pairs
Value may be more name/value pairs.
Address = '100 Main st'
Can only have 1 value per context.
Can be defined more than once.
Maps to a unique value
A name
Objects
Name/Value
Name
Name
Name
Of Name-Value pairs
This is the simplest definition in JS
A Collection
Name/Value
Name/Value
Name/Value
Name/Value
Name/Value
It's just that simple.
Key to the whole shootin' match.
Global
is root/base
Global Object
Creates 2 things
'this'
Accessable EVERYWHERE to EVERYTHING
Execution context
"Global": not inside a function.
external file demo
JVE loaded
Open Dev console
Run empty app.js
Created global execution environment
No script to compile
No errors
> this
>window
NodeJS: this = ?
There is always a 'this' in JS
Webpage: this = window
Each tab is its own global execution context
Different 'this' per tab.
root object is 'window'.
All unspecified objects become member/fields of 'window'
The Outer environment
But null at global level
Otherwise outside is available.
Your code.
Playing with variables
Can add more stuff
<^-arrow> last command
console.log(console + world)
var world = 'world'
console.log(hello);
var hello = 'hello'
In the console
var number1 = 10;
var number2 = 20;
alert(number1 + number2)
alert(hello + 1)
var isItRaining = true;
isItRaining = false;
Console is the playground.
JavaScript is Easy
inspect>console
about:blank
Teach a 6-year-old and an 8-year-old
In great shape if you've never learned any other languages.
Most accessible language ever.
4 + 6 = 10
SourceDecoded
etc.
JS has no concept of bytes or bits.
Reading Assignment: Booleans
&&, ||, !
The verbs in an expression.
What are operators?
+,-,*,/,%, &&,||, ==,===, >=,<=,!=, +=, -=, *=, /=
What logical operators do you know?
What binary operators do you know?
Read This
Boolean
Everything without a value is false.
Everything with a value is true.
Is implied in all comparisons (10 > 9)
NaN, Inf
null
false
Boolean(exp) is an expression true | false
undefined
""
0, -0
Can be objects
var y = new Boolean(false);
But don't. Bad practice.
var x = false;
== coerces types
x == y; % true.
obA == obB; % false
== always false for objects
=== does not coerce types
Quiz
false
5 > 4
false || false
true
true || false
true && false
((4*2)>3)&&((6-3)>20)
Playing with Booleans in the Console
a && b; % false
var c = true;
a && b; % false
var b = false;
var a = true;
a && c; % true
can have operators
&& is only true if both sides are true.
var d = a && b; %false
Put expression result in another variable
a || b ; % true
b || b ; % false
var k = false;
|| is true if either side is true.
b || k; % false
a || k; % true
(a && b) || c; % true
( a || b ) && (c && k); % false
Can combine expressions into bigger expressions
... more significant logical expressions.
Binding, Functions, and Control Flow
side effect?
a function
an environment?
a binding?
an expression?
control flow?
What is
conditional execution?
May or may not "return" or evaluate to a value.
May have side effects.
functional effect on the environment
JavaScript that evaluates to a single value.
An association between a name and a value.
A global/local hearchy of name/value pairs.
global/local boundaries are set only by function definitions
An ordered collection of executable JS instructions
May or may not be named (assigned as a value)
Unrelated to its return value
Structure that guides execution order
May contain
Loops
Function calls
Conditional branches
branching order of JS execution based on data environment
Collection of values at an exact time.
Sampler platter
Sampler Platter
concat()
join()
split()
indexOf()
impure: pop()
pure: length()
if, switch
for, while, do
sqrt()
Produces a value
print()
Produces a side effect
Give an example of a function that
Conditional execution?
if
Boolean evaluations
Keyword
Invokes
What kind of
while
do
Chapter 2: Functions
Techniques
Anatomy of a function definition
Start creating our own functions.
Increase our expressiveness.
Defining our own words inside a story
Definition Order
Local Variables
Nested Scope
The Stack
Function Values
Optional Arguments
Closure
Techniques
Recursion
Purity
Avoiding Repetition
Function Anatomy
'square' is the function's name.
keyword 'function' is always used to create a new function.
New function will be stored as a value if a name is given.
(list of arguments)
{ body }
Function body curly brackets are mandatory.
keyword 'return' assigns value to the function.
'return' ends function execution.
Return w/o value returns undefined.
Argument values are taken from the calling context.
Function may re-assign values to arguments.
Definition Order
As a seperate pass over the JavaScript
Doesn't matter.
Before any execution begins.
Interpreter collects all functions.
Local Variables
Variables created inside functions
Will be recreated every time the function is called.
Value will no longer exist after the function returns.
Creates new values at every callback or recursion.
External variables of the same name are untouched.
Local variables supercede global variables
'var' defines variables. Otherwise its just a reference.
Nested Scope
"lexical scoping"
Only functions create scope.
{ free-standing brackets are allowed } but do not create scope.
Functions defined w/i functions
No depth limit.
Variables local to parent are global to all children.
The Stack
Function contexts pile their local variables here.
FIFO
Limited memory for it per machine.
Function Values
Used in bigger expressions.
b( ) -> "call w/o arguments" operation
function ( ) { return value} <-- anonymous function
Everything in JS is a value, including functions.
Names of defined functions can be used as variables.
Passed around
Function contexts can be
Closure
JS preserves all accessable local variables.
Can return a child function that returns its global variable...after parent has returned.
Enables function factory patterns
Optional Arguments
Missing arguments are assigned undefined.
Extra arguments are ignored.
Can check vs. undefined to assign defalt values.
Expect to screw that up at some point.
Function Best Practices
Add simple things.
Collect repeated code into functions.
Less code = fewer bugs.
Less copies = easier mainenance.
Functions should only do one thing.
Functions should be named for their one thing.
Don't add too many simple things. That's a framework.
Purity
Means no side effects.
Determinant.
Will work in any context.
Self-sufficient
Likely more generalized, more useful.
But sometimes side effects are needed.
Recursion
Must be bounded.
Usually a less-elegant, but faster solution.
Begin with legibility. Retrofit for performance.
Function calls itself
Usually slower than a loop due to stack overhead.
Could cause stack overflow.
Best used on branching problems.
if-else
Can abuse HTML with JS document.write()
Now we're branching!
if - else always runs on Boolean values
false values trigger else blocks to execute
Can nest if-else structures
Quiz
if (false) { alert ("true!") }
Nope.
if ( true && false) { blah }
if ( true || false ) { blah }
Yes.
if (true) { alert("true!")}
Does it alert?
if( false ){ alert("true!") } else if (5<3){ alert("hello") } else{ alert("hi and hello!" ) }
hi and hello!
Loops Reading
Binding
Control Flow
Functions
While and Do Loops
while (condition) { body;}
for (var counter = init; counter ~= condition; counter increment) { body }
+=, -=, etc.
Dispatch on switch (condition) { case "value": body; break; default: body_d; break}
Homework
Loops
while-loops
Difference
Do-loops
Allowing us to do?
Looping control flow
What is
Get stuck forever.
Conditionally repeating code
Repeating the execution of code.
Condition checked after executing.
Condition checked before executing.
Repetitive boring tasks.
Process arrays
Style
Indent blocks with whitespace
useCamelCase
// comment
/* drone on with your comment */
More
Break and Continue
For loops
While loops
for Loop
Exercises
fizzbuzz
# tree
chessboard
Chapter 3
Aunt Emily's Cats
More theories
Basic Data Structures
Solving for Cats
Solve a text extraction problem.
Learn about
Object values
Arrays
Postscripts cat inventory events in e-mails.
Crazy cat lady
Reading Assignment
What is a pure function?
let
What's the difference?
var
Create a function?
How can you
scoped to function nearest { enclosing block}
Scoped to { enclosing block }
Not pre-processed. Not available before defined.
Preprocessed in first pass. Available before defined.
function name (parameter list ) { body}
Only affects return value.
Basic Data Structures
Object Values
Objects as Sets
Mutability
Objects as Collections: Arrays
Methods
Properties
New language features
More Theory
Tying Up a Loose End
The Math Object
Enumberable Properties
The arguments Object
range( start, increment end)
Math.sin( ) .cos( ) etc.
Intrinsic storehouse of all things math.
intrinsic properties are hidden.
Solving 4 Cats
Cleaning up the Code
the Full Algorithm
Extracting Cat Names
Finding Relevant Paragraphs
Separating Paragraphs
Date Representation
Gathering More Information
Data Presenation
Use an array to archive/access e-mails.
use .split( ) to cut strings on \n's
use .slice( ) to compare first 4 characters.
wrap .slice( ) in our own startsWith( ).
use .indexOf(':') to find name starts
Decomposition
Encapsulation
JS intrinsic Date object.
Parse more to get the date from fixed-format input.
Add more fields to our object type.
oldestLivingCat( )
getCatInfo( )
The Plan
Start with a set of cat names that has only one "Spot".
Take names from a paragraph
Remove names with "died".
Add names from "born"
Look for paragraphs that start with "born" or "died".
Parse e-mail archive in chronological order.
Find the : in the paragraph
Take the part after the :
Split this part into separate names by looking for commas.
Properties
Except null and undefined.
Attached to every value in JS
Named metadata
Two syntaxes
dot.notation
bracket.['notation']
Only works if
Valid variable name
No spaces or symbols in the name
Does not start with a digit character
Object Values
use the 'in' operator to Boolean if an object has a property with given name.
delete removes properties from an object.
reading non-existant properties returns undefined.
Values are assigned = as usual.
Each property is attached to an object by a name.
Objects are collections of {name : value} pairs.
Names can be any string, not just valid names.
Also = creates new properties.
Access invalid named values with ['bracket notation']
Brackets can contain any expression.
Expressions are coerced to strings.
Objects as sets
To track unique strings
Use 'in' operator to check if name is in collection.
Remove strings from set with delete
Assign any value
Make strings names
Set is a collection of unique values
Mutability
Asignment of values is by value.
Assignment of objects is by reference.
== sees different objects with same values as different.
Object values can change.
Objects as Collections (Arrays)
use [brackets, commas] to
define
JS is base 0
[ ] is the empty array
Arrays are objects.
access
[arrays] are intrinsic to JS
Elements are indicies
indices are not all valid var names.
Access indicies with ['bracket'] syntax.
style
i,j,k for indicies
If too many, then make more descriptive index var names.
Methods
intrinsic types have intrinsic methods
[ ].push(), [ ].pop(), [ ].join('_')
str.toUpperCase()
object values that contain code.
The arguments Object
Created at every function call
is an array
has a .length but no .push( ) or .pop( ) etc.
Used to loop over variable inputs.
Used to create optional arguments
Further reading
Using Parameters w/ Functions
Functions
multiple parameters
The return statement
Calling Functions from other Functions
Scope
Scope encapsulates or hides values
nested blocks (using let)
nested functions
functions
Global
Names may be duplicated across scopes.
Beware changing global values
Abstraction
Can combine functions to build larger functions
Rebuild multiplication from addition
Consider addition and multiplication
Can create very complex systems.
Build increasing abstraction layers.
Cancreate function heiarchies
Can bundle behavior in a function
Multiplication is an abstraction of addition and for/while
Don't care how encapsulated code is implemented.
Abstraction hides messy implementations.
Returning Values
Returned values can be assigned to variables at the calling line.
Can return expressions w/i function.
Each function can have ONE return value.
Exercises
countBs.js
isEven.js
min.js
Arrays
add values with spam.push('valueX');
base 0.
blah[0], blah[1], ...
var blah = [ value1, value2, ...]
Several related values in 1 variable.
Comments
/* block comment */
// one-liner
Explain.
Make it easier to
Read code
Ignored by JS engine.
For youself... tomorrow.
html: <!-- comment multiline -->
Writing good code is hard.
Clean Code
Recap
The Next Level
Not an expert.
Can read, but not write too well yet.
Will only get better as you go.
Promises
Next:
Libraries
Probably know more than 90% of people in the field.
Lego w/ other people's code.
Arrays
Callbacks
JQuery
Console
console.log instead.
But will have many variables in the workspace.
Could do document.write( '<p>'+blah+'</p>');
Inspect variable values
For dev output, not user-visible.
right click -> inspect
/elements: all webpage's code.
ALL JS CODE IS PUBLIC!
console.
write text: console.log('blah')
Can do so programatically in the JS code.
Can also inject JS code/variables etc.
Libraries
Lots of other schmoes help with testing and bug finding.
Somebody else worked out the tricky bits.
Why do we use libraries?
List of available functions
Read the Fine Documentation
real-world examples.
Don't re-invent the wheel.
Will be integrating jQuery
Enables software to scale.
jQuery
Written in JS
single .js file to link in
23 to 160kb source
MIT and GPL licenses
The most popular JS library.
Write Less, Do More
is
jQuery
Free to use.
1:10 to 1:20 efficency
Enables
Animated effects
Adding Animated effects for elements
Is great for
Drop-down menus
Creating image slideshows
Similar to Flash movies
Making XML (Ajax) requests
Manipulating the DOM
Fade
Slide
In/out
Get more data from the server
Expanding/ Contracting
Without reloading page
Add | Remove | Reorder
Displayed web page
Drag-and-drop interfaces
Client-side data validation
Cross-platform, cross-browser compatability
Minimized: no white-spaces: 23k
Uncompressed: 160kb
Shorter load times
Readability/ Maintainability
Button Alert Exercise
Use jQuery
Spawn an alert when pressed.
Create a button
Exercise in "day in the programming life"
Know what you want, but not exactly how.
Go look it up.
Text Input Alert Exercise
Create a button.
Show input text in an alert when button is pressed.
get text from input field to display.
jQuery text field input
Create a text input field
jQuery Selector
find HTML elements based on
classes
id
types
And so much more!
values
attributes
element selector
$("p")
'#id selector
class selector
$("#id")
Based on element name
Based on id attribute
$(".class")
finds elements with a specific class
And so on
The first <li> elment of the first <ul>
the first <p> element
<p> elements with class "intro"
current HTML element
All elements
The first <li> element of every <ul>
And so on.
$("*")
$(this)
$("p.intro")
$("p:first")
$("ul li:first")
$("ul li:first-child")
And so on
All even <tr> elements
All <button> elements and <input> elements of type "button"
All <a> elements w/ target attrib. value not '_blank'
All <a> elements with a target attribute value '_blank'
All elments with an href attribute
All odd <tr> elements
And so on.
$("tr:odd")
$("[href]")
$("a[target='_blank']")
$("a[target!='_blank']")
$(":button")
$("tr:even")
Functions in a seperate file
<script scr = "yellow brick road/spam.js"> </script>
Functions as arguments
setTimeout( @function, timeLimit)
Functions evaluate to name-value pairs.
Functions can be used as arguments
Adds flexibility
Adds complexity
Scale through abstraction
Anonymous functions
Makes programming more compact
Names imply reuse and importance.
Wasteful to name a function if using as a parameter.
Careful of the formatting.
For one-time use functions
Makes code more flexible.
function ( ) { <body> }
Iterating an array
Functional programming: use an 'each' statement
$.each(array, function (index, value) { <body>});
Chapter 4. Error Handling
Automated Testing
Handling Errors
Types of problems
Programmer Mistakes
Runtime Errors
Returning a special value
Exceptions
Error objects
Selective Catching
Cleaning up after exceptions
Unhandled Exceptions
Always need a disaster plan.
Want the program to fail early and clearly.
No type checking whatsoever.
JavaScript allows slop to run.
JS makes liberal use of 'undefined'.
Will error if 'undefined' is read.
Check input for 'undefined'?
Look up JS test framework
Check all possible input scenarios.
Dependant on system status
Caused by user input
Check at programmer discression.
Typically 'undefined'.
Can cause code clutter.
try { <body> } catch(error) { <handler> }
... finally ( <do regardless> )
error.message
Uncaught land in environment.
throw new Error("oops!");
Logged somewhere.
var InvalidError = new Error ("Invalid")
if (e != InvalidError) throw e;
alert("Invalid error")
assert ( )
Chapter 5 Functional Programming
Other functional tricks
Example: Recluse
Higher-Order Functions
Abstraction
Complexity quickly overwhelms maintenance.
clever ways of combining functions creates functional programming
Need a basic function vocabulary.
Abstraction
Assume a basic knowledge in the audience.
Express things in a much shorter and clearer way.
Talk in a language that deals with bigger concepts.
Hoisting
Most languages error on pre-calls.
Functions are defined in first pass.
Functions are "hoisted" (moved to the top)
Variables are allocated on first pass.
Varialbes are not defined on first pass.
Pre-call b( )
Creation
Two-phase creation
What's executing isn't what you've written.
Creation phase
Global object
this
Outer environment
Memory allocated for variables and functions.
Function handles have addresses.
Variables have addresses.
Variables are not assigned.
Whole function is placed in memory.
Execution phase.
placeholder: "undefined"
Variable values given.
Undefined
is a JS keyword
Means "the variable hasn't been set"
Not an error
is a value
initial default value for everything
Chapter 4: Data Structures, Objects and Arrays
Methods
Properties
Data Sets
Mutability
Objects
Array Loops
Strings and their properties
Rest Parameters
The Math Object
Destructuring
Further Arrayology
JSON
for (let entry of JOURNAL) {...}
shift/unshift do push/pop at array bottom.
.indexOf(<blah>) and .lastIndexOf(<blah>) find <blah>'s index
strings are intrinsics, not objects
.slice(), .indexOf(), .trim() .zeropad(), .padStart(), etc.
Have intrinsic methods, but can't decorate them.
agregate additonal parameters in an array
function blah(...varargin)
Math.max, .min, .sqrt, etc.
Really an intrinsic namespace.
Reference an array of arguments by its elements.
Reference properties of an object parameter by their names.
Example Problem: Weresquirrel
Lyantherope's Log
Computing correlation
Attempt to find causation of an effect.
Need daily log of activities and result.
Chapter 4 Questions:
Which Values do not have properties
What are "properties" in JS?
What variable type can store multiple values?
What problems cannot be solved with simple variables?
What are methods?
How can we access properties in a value (two ways)
null, undefined
[evaluates to] .dot notation
Properties of objects that bind in functions.
Collections of different typed data.
Elements of objects, either data or function results
Objects are type-agnostic collections of bindings.
Chapter 4 Questions 2
What about mutability of JS objects?
How do you define an object?
What problem do objects solve?
What are objects?
let blah = { } is mutable
let blah = { param:value;}
Providing name spaces for collections of functions
Identified containers of named bindings.
Agregating value of different types
{param, param}
Another encapsulation scope in addition to functions.
const blah = { } is immutable.
Chapter 4 Strings questions
What is serialization
Math object?
What are rest parameters?
Why can't you add new properties to string?
What is JSON?
use case?
Diff JSON vs. JS objects
string is an intrinsic type, not an object class.
Namespace for all JS math functions.
collect overflow parameters in function calls
Math.min, .max, .floor, .ciel, etc.
.log, .sin, .cos, .tan,. etc.
Pass data structures between processes.
JavaScript Object Notation
Serializes JS objects as text files.
All JSON "parameters" are double-quoted.
JSON is data-only. No methods are allowed.
Convert with JSON.stringify( ) and JSON.parse( )
Arrange structured data for serial transmission.
Data Sets
Indexed with [square brackets]
Comma, seperated
Written between [square brackets]
List of values
[evaluate to property names]
base zero (index is an offset)
Array
index is stored as property names
Properties
Property names are strings.
Almost all JS values have properties
dot.notation
[evaluated to property name]
Binding within a JS value
Except null and undefined
Common properties
.length (how many elements)
Methods
Parameters passed in (parent)
Accesed via .dot notation
push/pop
Array/stack methods on string
.properties that are functions
Objects
{defined within curly braces}
'in' returns boolean if object has property with given name.
Property bindings grasp values
Property values can be assigned using =
Use 'let' to define classes
Comma-separated list of properties
Arbitrary collections of properties.
.assign copies all properties to another object
Mutability
let <blah> creates mutabile objects.
Identities are bindings to objects in memory.
== compares identity.
const <blah> creates immutabile objects.
Objects are mutable.
JSON
No function calls.
Only simple data is allowed.
All "propertyNames" are double-quoted.
JavaScript Object Notation
JSON.stringify and JSON.parse
Comments are not allowed.
Seralizes data
Asynchronous Reading Assignment
Dispatched and returns later.
Asynchronous functions
diff
Synchronous functions
Needs to store "callback" functions to run when finished.
Runs immediately
What is "callback hell"?
Results are available immediately.
"structured" callback code.
Typically uses nested functions that cause "pyramids"
Ties execution into a bowl of spaghetti.
Written with top-to-bottom execution expectations
Which technique can help us solve callback hell?
Keep code shallow.
Split functions off shallow-ly.
Modularize function libraries.
Handle all errors locally.
Name all functions.
Async functions are executed remotely or involve the user.
Assume remote agent will ALWAYS screw it up.
Make the first parameter the error condition handler.
Create heiarchy of reuseable functions.
Blocks engine execution.
Does not block JS engine execution.
Use promises.
Use async/await
vs. Angular vs. React
jQuery is sufficient for our needs for now.
Learn jQuery first.
jQuery was the standard until 2015.
Learn Angular and then React later.
Angular and React steamline jQuery
Callbacks
Around UI-element events
Runs
around asynchronous functions
setTimeout( callback, time)
event-wise function execution
Callback issues
Creates a pyramid
"Callback hell"
Screws with execution order vs. human readable order.
Don't define callback functions inside callback functions.
Promises
Call/execute promise:
Write async promise code
var promise = new Promise( function (resolve, reject){})
A promise is a blueprint.
Un-nests and serializes callback hell
promise.then(function(){});
Cure for "callback hell"
Chapter 5: Higher-Order Functions
Filtering Arrays
Script Data Set
Higher-Order Functions
Abstracting Repetition
Abstraction
Transforming with map
Composability
Strings and Character Codes
Recognizing Text
Summarizing with reduce
Linquistic, abstracted solutions are more likely to be correct.
Abstract low-level tasks into a vocabulary
function repeat(n,action){ for(let i=0;i<n;i++){action(i)}}
array.filter(test)
Functional Programming
Apply function element-wise. Return transformed array
array.map(function)
Pure functions: no affect on parameters.
Provide (a,b) => a+b combine function
array.reduce(combine, <start>)
Gain readability, but might loose efficiency.
array.some(testFcn)
Don't use UTF-16 due to aliasing problems.
array.findIndex(test)
Abstraction
Skill: notice when you are working at too low a level of abstraction.
Talk about problems at a higher (more abstract) level
Hide details
Higher-Order Functions
Change other functions
Create new functions
Abstract over actions, not just values.
Math term.
Function that operate on functions
New types of control flow
Come in several forms:
function greaterThan(n){ return m=> m>n;}
function noisy(f){ return(...args) => {console.log("calling with",args);let result = f(...args);}}
function unless(test,then){if(!test)then();}
array.forEach(i=>console.log(i));
Script Data Set
year
Direction ('ltr','ttb')
Ranges (start/stop in unicode)
Name
Contains info about Unicode languages
living
Database of objects
link for more info
Chapter 6: Objects
Class notation
Classes
Prototypes
Methods
Encapsulation
Overriding Derived Properteis
Polymorphism
Symbols
Iterator Interface
Getters, Setters, Statistics
Inheritance
Maps
instanceof()
Just redefine property or method in an instance.
Commonly used vs. Object.prototype.toString()
Encapsulation
Divide programs into smaller pieces
Make each piece manage its own state.
Keep detailed knowlege local.
Interact through "interfaces"
Limited sets of functions or bindings
Abstrct the details.
Public methods and bindings
Private methods and bindings.
_names
Actually no JS enforcement of public/private.
Only document "public" interfaces.
Methods
=> functions 'this' is calling environment.
fcnName.call(this, params)
'this' always points to instance method was called on.
Usually needs to do something with the object.
Properties that hold function values.
Prototypes
Function.prototype
Object.getPrototypeOf()
everything based on Object.prototype
Fallback source for properties.
Object.create creates an object with a specific prototype.
Array.prototype
Most objects have a prototype.
Classes
Defines properties and methods with shared values across all instances.
Defines properties and methods
Protype is the JS class.
Make an object with proper prototype
Constructor
Instance-specific data stored in objects.
Defines the shape of a type of object.
Make sure it has expected properties
Use Object.create(proto)
new constructorFcn( ) does 'this' correctly.
Class notation
Currently only methods can be defined here (static)
All other functions defined in class{ } are attached to the class prototype.
constructor function name binds that function as a constructor to the class name.
Allowed to omit class name in its definition (anonymous)
Using class in a statement produces the constructor as a value.
Static properties can be added to the prototype after the class { } stanza executes.
class keyword looks like a normal typedef class.
Maps
Object.keys() returns object's properties-- without prototype fluff.
has(), get(), set() are methods, but won't interfere.
JS Map type exists to be a Python Dictionary
Can't use object properties as a dictionary because prototype methods are added.
hasOwnProperty instead of in ignores prototype.
Polymorphism
Works with any type that supports that interface.
Code written to an interface
Symbols
Useful for defining un-clashable function names.
Converts from/to string.
let sym = Symbol("name")
obj[eval2Symbol]()
obj[eval2Symbol] = used as a binding
Runtime-registered, unique label set.
Iterator Interface
result is an object with a .value property
iterator.next returns next result.
returns an "iterator" interface
next, value, and done property names are not symbols.
.next value returns a .done property true if no more results, false if otherwise.
.value property provides the next value
Symbol.iterator
Create iterator classes with next() methods.
Getters, Setters, and Statics
"static" stores methods on the constructor.
Put set in front of method name.
Put get in front of method name
Does not have to access stored values.
Temperature.fromFahrenheit(100)
Can return calculated results
Inheritance
Constructs heiarchies.
Use "super" to access superclass methods.
Use "extends" to assign superclasses.
Chapter 8: Bugs and Errors
Debugging
Testing
Types
Strict Mode
Language
Error Propagation
Exceptions
Cleaning up after exceptions
Selective Catching
Assertions
Executing in the Terminal
console.log() redirects to terminal.
Runs .js files in terminal
NodeJS
Key Takeaways
Loops
Variables
Basic JS features
JavaScript provides logic for HTML
HTML provides bones for websites
Lists
Arrays
Document Object Model (DOM)
Callbacks vs. Promises
jQuery
Arrays
index accesses
0
Bind a name to a list of data elements
Do arrays do?
In an array?
The 1st element
What
Index lists of data elements
Use intrinsic functions to manipulate data
[ ].push(), [ ].pop(), [ ].join('_')[ ].push(), [ ].pop(), [ ].join('_')
Assignment
What is the otput when you type...
2=="2"
2==2
"cats".length
typeof("2")
typeof(2)
2==="2"
true
true
false
4
"number"
"string"
Why?
Why?
Why?
=== does not coerce types
== coerces types
There are 4 cats-- er...CHARCTERS
jQuery Selecting Elements
With jQuery
with a button
Access
element <p>
<div id="section1"
.hide(<speed>, <callback>); // it.
10 different <h1's
Current HTML element
All elements
class="test"
id="test"
$("div #test:first" ).hide()
<button type = "button"
$("p")
$("#test")
$(".test")
$("*")
All <p class="intro"...
#Compound $("p.intro")
All <a> w/ a "_blank" attribute value
First <li> of the first <ul>
First <li> of every <li>
#first <p> element
All <a> w/o a "_blank" attribute value
$(this)
all elements with href attrubute
$("a[target!='_blank']")
$("p:first")
$("ul li:first")
$("ul li:first-child")
$("[href]")
$(a[target= '_blank']")
All even <tr> elements
All odd <tr> elements
All <buton> elements and <input> of type="button"
$("tr:odd")
$("tr:even")
$(":button")
onclick =
'$( "h1" ).slice( 0, 10 ).hide()'
> HideH1's </button>
ES6 Features React Loves
"Spread" ... Operator Overloads specific fields in an object.
"destructuring" = "deal" in Matlab.
... "rest" parameters absorb call parameters into an array.
Scope var, let, const
Shallow vs. Deep Copy
Arcane JS Wrinkes
Arrow Functions
Compact alternative to a function expression
Cannot use yield wthin its body
Can not e used as constructors
Not suitable for call, apply and bind methods
Does not have arguments object
Does not have its own bindings to this or super
Execute in scope they are created, not in calling scope.
Asynchronous
JS is single-threaded
await waits for function finishes.
Chaining dependent async code creates "callaback hell"
Runs between the stack, que, and Web APIs.
Async code will give way and wait.
async returns a promise.
async modifies functions
Promise
Solves callback hell.
.resolve(value)
Constructor: paramFn(resolve(), reject() ):
Rejected
Fulfilled
Pending
3 States:
.reject(reason) returns a rejected w/ given reason.
.all(iterable) Wait for all promises to be resolved/rejected
.allSettled(iterable) Wait until all promises are settled.
.race (iterable) wait until any is resolved.
Instance methods
defaults if no onRejected defined
.catch(reason)
finally() executes after all returns
.then( onFulfilled, onRejected )