Intro
Questions
Q1 Why are you taking this course?
To enable me to create a modern interactive front end for my web app.
Q2 What technologies and techniques will you be using to build your online resume in this class?
jQuery, JavaScript, DOM manipulation, HTML, CSS, a pro text editor, Browser Dev Tools, Git and Git Hub... maybe that Python tutorial visualiser for JavaScript. Follow-up: goshdarnit, that visualiser is gone!
Key Ideas
1. Why so much HTML?
Everything in JavaScript (at least, in this course) works on HTML and CSS via the DOM, which it sees as a JavaScript Object. JavaScript can also be directly in the HTML, or preferably reference from a separate file with <script> tags.
2. Referencing Elements
Note that referencing an HTML element using #example
is looking for the unique identifier id="example"
. And that getElementByID
says singular 'element', because it is an ID. Other references will use 'elements' plural.
3. jQuery
This course will use the third party library, jQuery. It is a good idea to get used to the idea of using third party libraries. jQuery had an .append()
method that allows us to add text to an HTML element. To get an HTML element ID with jQuery, type $("#elementIDvalue")
will reference the element, $("#main").append("some text")
will append some text to it.
4. resume.js
This course will be completed in resume.js, the other files contain helper data.
5. Running JavaScript in the Dev Tools console
The big browsers have 'Dev Tools' that we can use JavaScript directly with. Chrome has a JavaScript console that we can type directly into and have it parsed. Note that using console.log()
returns undefined
, this is because it prints to the console as a side-effect, it does not return anything.
6. More Dev Tools
Note that you can view and manipulate any webpage you visit using Dev Tools by messing with the HTML, CSS and JavaScript. You can execute any old JavaScript in the console, like multiplication, division etc.
7. Variable Syntax.
var varName = value;
Note that objects, arrays and functions use the same syntax.
8. Semicolon style
Note that all statements in JavaScript shall end with ;
this is not always needed but omitting it can cause problems when you least expect it you'll have trouble finding that this was the root. Compare this with Python which never uses ;
but uses line returns as part of the language.
Data Types
1. Elements and Data Types
Note the several different Data Types, for now we'll just work with strings and numbers. All numbers are 64 bit floating point. There are no integers and no number conversions required.
2. String Replace Method.
"string".replace("old", "new");
"string".replace(/regex/ig, "new");
i
= ignore case, g
= global (replace all results of the search, not just the first). See MDN for loads more string.methods()
3. jQuery append and prepend
Note .append()
and .prepend()
work inside the container they find, they don't append after or before the container, they add content as if a child or children, at the beginning or end.
4. Zero Indexing
Remember indexing an Array []
(and strings) starts counting at 0, so array[0] is the first item of the Array.
5. Concatenation
You can concatenate text with +
"string1" + " " + "string2"
will return "string1 string2"
.
6. More String Methods
str.toUpperCase()
converts to upper casestr.split([separator[, limit]])
separator is typically a space, comma or tabstr.slice(beginSlice[, endSlice])
if no endSlice is specified, it will take everything up to the end. Note beginSlice starts counting at 0
We also used the string methods, and noticed that strings are immutable, unlike Arrays. You can't alter a single letter in an string, it has to be split and joined into new strings.
7. We learned about:
str = arr.join([separator = ','])
need to remember that this is an array method, even though it is commonly used on strings.
8. Truthy and Falsey.
The 7 Falsey objects are:
0
,""
(the empty string), andfalse
all are==
to each other (3)null
andundefined
only equal to themselves (2)NaN
not even equal to itself, useisNaN()
to test for it, if needed.typeof(NaN)
is"number"
(1)
Some surprising Truthy items are:
[]
The empty array{}
The empty object"0"
A string with 0 in it
Note Booleans true
and false
are lower case.
9. Infinity has both positive and negative versions.
10. The difference between ReferenceError
and undefined
...is that undefined
has a variable names but no value assigned. ReferenceError
means the variable has not been created. null
is an intentional undefined place-holder value for a variable name. undefined
is unintentional. undefined
can cause serious debugging issues as bugs happen in places where they didn't originate and can be very hard to trace. Using a lot of assertions can help avoid the issue.
11. Arrays. []
is object literal, e.g. var myArr = [];
Array methods:
.push()
appends the argument to the array, returns new length of the array.pop()
cuts the last item off the array and returns it.split()
uses the parameter to split the string and return an array.join()
joins all items of an array into a string
Style: open square bracket on declaration line, newline and indent each item, commas between items, no trailing comma, close bracket at same indentation as declaration.
var myArr = [ "item", 23455, false ]Note arrays use zero indexing.
12. Objects. {}
is object literal, e.g. var myObj = {};
Object referencing:
- Dot Notation:
name.value
best for code readability, code needs strict style to work with this though. - Square Brackets Notation:
name["value"]
works for (badly) named variable, but can also be useful for certain situations. - Style: Same as array for layout. Items should be
"name": value
, note that name must be a string, items are separated by commas so a trailing comma after last item should not be there.
var myObj = { "name": "value", "namen": 2343, "manem": true }Add items too an Object with:
object.name = value;
or the equivalent bracket notation:object["name"] = value;
13. JSON (JavaScript Object Notation)
It is (not quite) a subset of JavaScript, it's very useful for site syndication as it is more flexible that RSS or XML. The style is very important and, although it is simple, it can get messy easily so using a service like jsonlint.com is a must.
The main differences between a JavaScript object and the JSON standard format are:
- Double quotes must be used for property names
- Trailing commas are forbidden
- Leading zeros are forbidden from numbers
- A decimal point must have at least one trailing digit
- Certain character can be escaped, it gets a bit technical here... cross that bridge later
JSON.stringify(object)
converts and object to JSON.
14. More HTML, CSS and DOM stuff
Note that using document.getElementByID("something")
return the full HTML snippet. To set a CSS with JavaScript use the syntax: document.getElementByXXX.style.property = "value";
Note Javascript and CSS references will not be exactly the same e.g. background-color != backgroudColor
Flow Control
1. if
/ else
and comparisons
An if
/ else
statement syntax is:
if (condition) { //code to run; } else { //code to run; }Note the else block is not required and there's no trailing semi-colon after the condition or after the if and else blocks.
Comparisons can take strict and loose form, the strict forms like ===
and !==
are safer than loose, ==
and !=
which most people say never to use because it first tries to convert both items to the same type and then evaluates the comparison.
You can also use less than, greater than and with less or equal etc<
, >
, <=
, =>
. These can evaluate to true
of false
and be used in the if statement's condition.
Note the ternary operator would make short work of the example if / else syntax given above.
2. Loops: while
, for
, for
-in
. pseudo-selector :last
DRY - don't repeat yourself
While Loop
syntax:
while (condition) { //code to loop }Note, no trailing semi-colon
For Loop
syntax:
for (var i = 0, i < 9, i++) { // (initialization, end condition, mutator) //doSomething(); }Note, initialization defines how to start, condition defines when to end, and mutator defines how to increment the iterator.
Notes: no trailing semi-colon, use var when declaring i, or better initialize an incrementer variable before the loop.
For-In Loop
syntax:
for (item in object) { //doSomething(); }Notes:
- Iterates through every item in a collection of items.
- '
item
' is like a function parameter - it can be named here for use inside the loop. This refers to the item's index in an array or name in an object. - '
in
' is a keyword that must be used for the for-in loop - '
object
' is the name of the collection to go through
(note: found and used the jQuery .each()
method, more notes in the code)
Lastly we came across jQuery's :last
selector which gets the last item in a group of items with same class name like .class
There is also :first
and :last-child
and :first-child
It is used inside the quote marks like $.(".class:last")
. Pseudo-selectors, now for more than just :huvvers!
I decided after this exercise to use a variable naming style for now in my projects, especially while learning. This means appending 'Indx' to index names and 'Arr' to arrays because even though the instructors gave a clue about the problem that would be run into, and I noticed the clue, and was watching for it... I still made the mistake.
3. Functions
"Spaghettified": a mess of if statements and loops. Using functions can chunk code into more meaningful and logical groups, or 'bundling complicated groups of instructions together' as described by the instructors. The thing is; they'll probably recommend simplifying and shortening these functions later!
"Spaghettification" is something entirely cooler.
Function expression syntax:
var myVar = function (parameters) { //bundled code to run; }
This is an anonymous function assigned to be returned by the variable myVar
and is run when called by myVar(); or passed like console.log(myVar);
This syntax can also be used un-anonymously by assigning a name to the function as well, this can be useful when using recursion. Anonymous functions can also cause confusing when debugging.
Function declaration syntax:
function myFunc(parameters) { //bundles of code go here; }Declared functions like this get 'hoisted' to the top of the scope with their blocks of code. Function Expressions only get their variable names hoisted, and set to
undefined
until called directly or passed.
4. Collecting clicks and the event object
I'm still having trouble with:
- event objects
- callbacks
There was some more difficulty here about 'loc', turns out this was the same as using 'e' as an event object. http://forums.udacity.com/questions/100255989/re-loc-the-jquery-documentation-link-given-here-doesnt-mention-it
need to spend some time to understand this 'event' thing http://api.jquery.com/category/events/event-object/
I don't even know what the point of this exercise was, what was is showing?
5. Return Statements
Dev tools demo showing how to access the different files referenced from a web page. This led to finding a return keyword and statement. He explained this was why console.log() shows 'undefined' on the console. It doesn't return anything. This is also known as a pure function, the console printing is done as a side-effect. Apparently this is how Haskell mostly works and why the joke says it is a 'useless' language.
He showed how "string split".split(" ");
returns and array. Quiz also gave exposure to .push()
and .pop()
. Push appends and item to an array by mutation and returns the new length of the array. Pop return the last item in the array and deletes the item from the array.
6. Internationalization
This was a bit of revision the let us create a new function, do some string manipulation and return stuff. It also demo'd some 'interactivity' by using a button to change a page element. Nothing new here, just some timely practice.
7. Encapsulation
Encapsulation means 'hold inside'. In terms of objects and functions, the lesson seems to be teaching that you can put a function inside an object by assigning the function using dot notation, making the function a method of the object. This was the lesson that linked to the excellent helefant.com, from where I went into a total rabbit hole for several days.
Follow-up: encapsulation here means the functions can belong to the objects, but aren't necessarily written inside them. This will allow me to keep the object property methods outside the JSON, so it can validate, even though the function will still be 'encapsulated'.
8. Exploring new syntax
James noted the 3 different syntax to create objects: literal, dot and brackets. He noted JavaScript had been around for a long time and has gone through many changes, stuff you see today may be old and outdated and not suitable to use any more.
They revisited the Click collector as a challenge to figure out what's going on. But since the answer was just to show that an anonymous function can be passed as a parameter, it didn't actually help understand anything about events etc.
They also remind you to look stuff up in Google... I did note the notes mentioned that: "some libraries ask for a callback function to be executed once they have the results ofa task." But still found no explanations or help anywhere...
9. Customize / The Final Project
They talked about 3rd party libraries like Google Maps and D3, which I will look into as needed, personalizing the resume with CSS and adding the map to the resume page, which really was just uncommenting some code. More of a demo of the 'further cool things you can do with JS' kinda thing, which is ok.
The instructions were a mess in this one though. Even the final project is very vague, yeah you can do it like that but it shows a lack of effort. Anyway I'll get a much more exacting picture of what to submit from the Nanodegree details.
Post Course Notes
TODOs
-
DONE: Research learn and understand events
Very, very basically, events get attached to HTML elements so that something the user does to the element (like clicking, hovering or even typing) can be used in JavaScript. Like the way jQuery grabs an HTML node from the DOM and returns it to you to do something with it, the events is sent back to you, so you can interact with the user.
-
TODO: Research learn and understand callbacks.
-
TODO: find out the difference in the placement of these parentheses in anonymous self-executing functions.
-
DONE: Find out the meaning of 'formal' in 'formal parameters'
Formal parameters are those defined in the function definition, actual parameters are those that are passed in when then the function is called.
-
TODO: Understand how Closures can be dangerous according to the Udacity Style Guide.
More about Scopes
Functions create scope, not blocks.
Variables created inside scope only live inside that scope, they call also live inside child scopes, but not inside parent scopes.
Closures are an interesting idea that allow us to simulate private and public functions, they let you make an enclosed function object that returns methods to make them public and normal but enclosed methods remain private. If that doesn't make a lot of sense summarized, see the resources file for links to pages with full explanations and working examples.
To simulate a block level scope you can wrap a block's code in an anonymous function, creating a 'temporary' scope.
(function() { //code; }() )
and (function() { //code; } )()
are both kind of like saying "var f = function(){//code;}; f();
" the trailing empty parentheses executes the code in the anonymous function, like calling itself (is this callback?) and this is the function's closure?
In other words everything inside the function is enclosed because it starts its own scope, executes and finishes all in one.
Note the trailing parentheses are either outside the function or just inside the closing bracket (added a TODO for this)
Functions as Objects
Functions are first-class objects, which basically means you can do anything to them that you would do with a variable, like assign them to variable, pass them as parameters, and return them from functions. Note: console.log(myFunc instanceof Object); => true
'Hoisting'
Declared functions and variables are always hoisted to the top of the scope before any other code is run. This:
function () { bar(); var x = 1; }actually becomes this:
function () { var x; bar(); x = 1; }
The resolution order for hoisting is:
- language defined (this, arguments)
- Formal Parameters
- Function Declaration
- Variable Declaration
NB; never use 'arguments' as a formal parameter. If multiple formal parameters have the same name the last one will take precedence (even if undefined).