Zero to One: Building Mamoru – Weeks 3 and 4

This post is part of a series, “Zero to One: Building Mamoru from the Ground Up.”

My goal is to learn javascript properly, so that I can code my Hackathon-winning app “Mamoru” into reality. I’m using cordova, which is a cool tool that lets you use CSS and js to build multi-platform phone apps.

Summary of curriculum for Weeks 3 and 4. *Note that I skipped Chapter 7, “Function Expressions.” With the basics under my belt I am giving myself more freedom to skip readings as I see appropriate. Otherwise there’s just no way I would actually get to building Mamoru!

If you’re having trouble copying code examples into JSFiddle, it’s probably the quotation marks. They get turned into fancy, “smart” quotes that JSFiddle doesn’t like. Just replace them with standard quotes and you’ll be fine.

I would recommend reading Chapter 5 of Professional before reading the blog post on Javascript Objects in Detail. If you are new to programming (i.e. you don’t already have an idea of what ‘prototype inheritance’ means), I would recommend skipping the blog post and just reading the “Understanding Objects” part of Chapter 6 of Professional.

Once You’re Done With It, Delete It

One of the best habits I’ve made is to be unafraid of deleting code and writing it fresh (i.e. when working with code examples in JSFiddle). I used to always hold on to whatever I had written and try modifying it before writing something new, but now I just rewrite. I don’t intend this advice to apply to actual software projects, but instead to writing a function, or writing a for loop. I don’t just write one for loop and then keep it around, endlessly editing it. Instead if I want a new for loop, I write it. If I’m done looking at an example of a certain function constructor, I erase it (instead of commenting it out “just in case” I need it again later on).

This has made me much more confident in myself, and has led to greater retention of syntax and a greater ability to translate “what I want to do” into working code. All around a great thing to do, and it feels wonderful to be ridding myself of the “training wheels” so to speak.

Knowing which Parts to Scan

Technical books are not like other textbooks. There is material in a technical book that is explicitly meant for you to skip over. It’s reference material, so that later when you want to know how to get the year of a date formatted in a certain way you know you can look up the Date Type and the information will be there.

You don’t need to waste your time typing every one of the 20 method calls for Date objects into JSFiddle and experimenting with them. You’ll miss out on the big picture and will end up retaining less, plus you’ll be using the book inefficiently. Let it do work for you.

On the other hand, don’t use this as an excuse to skip reworking code examples that help you learn concepts or fluency with syntax!

Links for LJSP Weeks 3 and 4:

Stack Overflow Questions

1. To var or not to var – You should use var to declare your for loop’s counter variables. I think I may have actually covered this earlier, probably in some reading about scope/execution context, but Stack Overflow is helpful for refreshing exactly these kinds of small questions that would take a while to find looking through notes.

2. How to print objects – There are as many methods as there are use-cases, it seems! Useful for debugging purposes, though in the reading we found defining a custom function for toLocaleString() and then calling objectName.toLocaleString() to be sufficient!

3. Summing up the digits of a number – Technically not a Stack Overflow post (from learnjavascript on Reddit instead), but pretty interesting. I scanned over this poster’s code and wasn’t sure where the mistake was. Reading this response identified a *ton* of mistakes. Even after studying intensively the last 1.5 weeks, I didn’t see those mistakes. Trying to fix other people’s code is a good way to make sure you’re understanding how all the parts of a language fit together, and to make sure you don’t get your different languages mixed up!

4. LILO vs. FIFO Queues and array.unshift()What is the difference between using array.unshift() and array.pop() to add/retrieve from the head/tail of a queue, and using array.push() and array.shift() to add/remove from the tail/head of a queue?

*This question is a good opportunity to highlight two important things when using Stack Overflow. One, if you have a proposed answer to your question, include it. It shows that you have done work. Two, if you have done research to try to answer your question before asking it (which you should have), include it. It shows that you have done work. Users of SO are very sensitive to whether posters do work, so signaling that you have should be considered a requirement for asking your question. Otherwise you end up with downvotes and no useful answers (thanks to Jonathan M for the helpful answer in the comments).

5. Ten most common javascript mistakes – some of these are beyond my level right now, but I totally fell for the block-level scope mistake, even though I have it in my notes from last week! There is no block-level scope in javascript. There is no block-level scope in javascript. There is no block-level scope in javascript!

6. Why you should not use frames – all the reasons you should appear to be solved by other tech! Helped me relax a bit in the Ch. 8 reading about frames that made no sense to me…

7. Use em (not px) and percentages (not px) for font-sizes and widths/heights in CSS. Doing so lets content flow naturally when the user zooms and adapts itself gracefully to different form factors. With mobile in mind, the <body> element should set its font-size using a %, and the rest can be set using em.

8.  What kind of object is it? – A question about a getElementById() example from p. 365 of Definitive. Some time later, I came up with my own answer thanks to the Mozilla Developer Network documentation. For questions that require digging into how and why javascript is behaving in a particular way I don’t find StackOverflow’s initial wave of answerers to be very good. Sometimes an answer already exists in another question, or you’re blessed with someone knowledgable, but it’s clear that there is a large number of developers on SO who appear knowledgable but don’t actually grok the fundamentals at a core level.

Resources (I got tired of adjusting the index every time I wanted to add to the beginning…)

-1. Programming Javascript Applications by Eric Elliott – the whole book is online for now. This looks like a good resource, perhaps for after Mamoru or even during it, for example the “Anatomy of a Typical Modern JavaScript App” section and the Authentication section seem useful!

0. Stubbornella’s CSS guide – I will return to this and read it thoroughly before making Mamoru. I feel like this is a great place to get good best practices habits ingrained.

1. Two different viewports for mobile – the layout viewport (which acts like the desktop viewport, basically, and is fixed) and the visual viewport (which can change in size and orientation). This will be a helpful article to read when developing a website for mobile.

2. JSHint – For some reason this tool is called a “Linter”, but basically it gives you hints on how to make your javascript syntax better / catch some errors. They have a plugin for Sublime Text 2 and 3, so I’m grabbing this asap!

3. Idiomatic guide to writing clean javascript – some great ideas here about how to make your code very readable. Scroll down the Readme until you get to the examples. I’ll definitely incorporate some of these ideas, like space around the conditions in an if statement!

4. Kangax’s compatibility table for ECMAScript 5 – Shows which browsers support which Javascript calls.

5. Android Developers Dashboard – shows current fragmentation by OS version for Android devices. Good idea to make sure your app works on all OS’s with significant install bases!

6. HOODIE – A very cool project to create a way for people to make apps without having to worry about a backend. They call it “noBackend” and their “dreamcode” (as in, “I have a dreamcode”). It’s actually part of a social mission to empower people to host their own services and data, which would be really cool from a privacy/usability standpoint. Definitely check it out! Not something I think I’ll be using now, but maybe in the future after I’ve learned and developed some apps the old fashioned way.

7. “OOP in JavaScript: What you NEED to know” – Richard’s post on JavaScriptIsSexy that might clear up some confusion regarding private/public properties/methods and how to use them.

 

6/25/2014 (Wed)

Gonna crush through Codecademy, and then move on to Weeks 3 and 4 (Objects, Arrays, Functions, DOM, jQuery). Today I spent the morning mopping up the rest of Weeks 1 and 2 (Introduction, Data Types, Expressions and Operators).

Wow is Weeks 3 and 4 beastly or what. A ton of reading (8 chapters!), some final Codecademy crushage, then a brief detour back through HTML + CSS + JS in the “Basic Projects” section of Codecademy, and then finally on to some more javascript with the Try JQuery course – another whole entire course!

This is a ton of work…But not too bad, considering that I finished Weeks 1 and 2 in six and a half days, so just under a week. Hopefully I can crush through Weeks 3 and 4 similarly fast.

Then we have our big project, basically a midterm project – building a web quiz. After that it’s Weeks 5 and 6 (Regex, Window Object, Events, jQuery) and Weeks 7 and 8 (Classes, Inheritance, more HTML5).

I can see that getting these notes formatted into posts sooner rather than later will be very helpful for me, as reviewing notes is harder than reviewing nicely formatted blog posts. I’m going to take a break now to format all my Week 1 and 2 stuff into a post.

What I did:

1. Finished Section 4 (“While loops”) of Codecademy Javascript

2. Finished Section 4 (“Control flow”) of Codecademy Javascript

3. Formatted the past week’s notes into a blog post.

Cool things I learned:

1. It takes way long to format these notes into posts, so I should probably just take notes in blog post form from here on out.

 

6/26/2014 (Thurs)

Time to dig in to Weeks 3 and 4 seriously. Spent yesterday getting things cleaned up and ready for the transition. Time to take on some more javascript!

Okay, I definitely see the value of typing code examples into JSFiddle and making them your own (e.g. changing the variable names involved, adding your own functions). It’s key to not just copy from the book but instead understand what was written in the book and what it does. When you do it you suddenly find yourself saying “oops forgot a brace here, oh yeah I need a comma not a semicolon here” etc.

I think making all these little mistakes is inevitable, so getting them out of the way sooner rather than later clears mental space for learning and retaining concepts instead of syntax. And hopefully for marrying concepts to syntax, so that you really increase fluency in the language. This is a crucial learning strategy to employ.

Also, this reading is taking far longer than I thought it would. Definitely not the rapid rate of progress I was hoping for. Hopefully though going slow through the readings and trying out the code will pay dividends later!

What I did:

1. Starting reading JavaScript Objects in Detail, but decided it wasn’t thorough enough for me. I’ll leave prototype inheritance for another day. It seems like a more complicated topic that I don’t need to be in a rush to master.

2. Read “Understanding Objects” from Chapter 6 of Professional Javascript for Web Developers. Much more thorough explanation than the blog post on objects.

3. Read “Problems with Constructors,” “Problems with Prototypes,” and “Combination Constructor/Prototype Pattern” from Ch. 6 Professional

4. Started reading Ch. 5, “Reference Types” from Professional

Cool things I learned:

0. ECMAScript 5 may not be fully supported in Android browsers older than OS version 3.0. This accounts for ~15% of Android devices on the market. Fortunately, it appears that Object.defineProperty() is supported, something I could verify when I visited kangax’s compatibility table with my 2.3 Android browser.

1. Objects are pretty sweet. They’re unordered lists of name:value pairs. Pieces of data are called properties (myBookShelf.genre for example), while functions are called methods (myBookShelf.sort() for example). They are basically just complex, compound data types.

2. Syntax for creating an object (“object literal”):

var favoriteBook = {

title: “The Fellowship of the Ring”,

author: “Tolkien”,

howGoodIsIt: function() {

console.log(“really really good!”);

}

}

You can also create an object like this (“object constructor”):

var favoriteBook = new Object();

favoriteBook.title = “The Fellowship of the Ring”;

favoriteBook.author = “Tolkien”;

favoriteBook.howGoodIsIt = function(){

console.log(“really really good!”);

}

3. Objects can have nested objects inside them! – In other words, a property of an object can be…another object!

var book = {name: “A tale of two cities”};

var nestedBook = {name2: “Second name”};
book.secondProp = nestedBook;
alert(book.secondProp.name2); //”Second name”

4. A much better way to make objects is to use a constructor function – this way you have one function responsible for the generation of particular objects, making it a lot easier to modify or maintain.

function Program (theName, thePurpose, theOS, theCost){
this.name = theName;
this.purpose = thePurpose;
this.OS = theOS;
this.cost = theCost;

this.showName = function(){

alert(“The name of this program is ” + this.name);
}

this.costInYen = function(){
var yenCost = this.cost * 100;
alert(“The cost of this program in yen is ” + yenCost);
}
}

var word = new Program(“Microsoft Word”, “To help with writing papers”, “MS Windows”, “85”);

5. Using getter and setter accessors – to use the getter and setter functions, you do not need to do a traditional function call. For example, for the Program object above we could do word.costInYen(); and get 8500 back.

To define a get or set function you need to use Object.defineProperty

var shop = {
name: “Little Shop of Horrors”,
_inventory: [“worms”, “totems”, “charms”]
};
Object.defineProperty(shop, “inventory”, {
get: function(){
return this._inventory;
},

set: function(newStock){
this._inventory.push(newStock);
}
});

You might think that using the get function would require a call like shop.inventory(); and that the set function would require shop.inventory(“wands”);. They do not. Proper calls are as follows.

alert (shop.inventory); //”worms,totems,charms”
shop.inventory = “wands”;
alert (shop.inventory); //”worms,totems,charms,wands”

Tricky tricky! I think this difference is because you’re not actually calling a function when you call the accessors get and set. Instead,  you’re accessing a property of an object, which then turns out to be a function and does some stuff. So in the set example when you assign the property to take a value it takes that value, passes it to a function, and that function pushes it onto an array.

6. Re: “Combination Constructor/Prototype Pattern” in Ch. 6 of Professional (p. 197). I think this is what Richard from JavaScriptIsSexy is referencing when he says Zakas has a preferred method for building objects that is neither the constructor nor the prototype pattern.

Briefly, Constructors have a problem because they make new instances of class methods (functions) for each object constructed. In reality though, you only need one function that does the same thing for all the objects. But, putting those functions in the global space is messy.

Prototypes have a problem because if they contain a reference value then editing a reference value on an object (say person1) initialized from a prototype will edit all the values on all the objects. So if we say person1.friends=”Bob”; then person2.friends and person3.friends will also change!

The solution is the combined Constructor/Prototype pattern for creating objects. We let the Constructor define object-specific properties (primitive and reference variables), and we let the Prototype define methods (functions) and shared properties (a single property whose change you want to see reflected in all instances of an object).

Here’s what it looks like in action. Note that the inventories are distinct and writing to one does not write to the other. Note that the methods are identical.

function Store(name, yearOpened, inventory){
this.name = name;
this.yearOpened = yearOpened;
this.inventory = inventory;
}

Store.prototype = {
constructor: Store,
sayInfo : function() { alert(this.name + ” opened in ” + this.yearOpened + “!”); },
sayInventory : function() { alert(this.name + ” has ” + this.inventory);}
};

var firstStore = new Store(“Charms ‘n Things”, 1208, [“wands”, “spellbooks”, “potions”]);

var secondStore = new Store(“The Armory”, 1465, [“chainmail”, “morningstar”, “broadsword”]);

secondStore.inventory.push(“buckler”);

alert(firstStore.inventory === secondStore.inventory); //false

alert(firstStore.sayInventory === secondStore.sayInventory); //true

7. Context specific code – the meaning of symbols can change based on their context. The { symbol (left brace) signals the beginning of an object literal in an expression context, but signals the beginning of a code block in a statement context.

//expression context

var dragon = {

name: “Jennifer”,

age: 5000,

superpower: “breathes fire”

}

//statement context

if (Jennifer.age > 3000) {

alert(“An ancient dragon has appeared! And its name is…Jennifer…”);

}

The notion of a symbol having more than one meaning based on context is pretty cool. I’m not sure if we call whatever evaluates (executes) JavaScript a compiler, but whatever the logic is behind it that process is pretty sweet.

 

6/28/2014 (Sat)

I skipped yesterday! I went to help a friend shoot the first episode of a new youtube series he’s launching called Standard Definition. Got to hang out at the Youtube Studios in Chelsea, shoot and give some direction (and pull sound, and script supervise…at the same time lol). It was a ton of fun, and their script/execution was great! Looking forward to seeing them continue!

Luckily I worked past 3 hours on Thursday, and am putting in some work over the weekend to stay on schedule.

What I did:

1. Kept reading Ch. 5, “Reference Types” of Professional

Cool things I learned:

1. Typeof — I had been wondering what the point of typeof was, since if you made a variable you ought to know what type it is already. Zakas gave a good example, which I’ve modified to make my own (don’t just copy from the book…understand from the book!).

function displayArtist(args){
var output = “”;

if (typeof args.name === “string”){
output += “Name: ” + args.name + “\n”;
}

if (typeof args.albums === “number”){
output += “Has made ” + args.albums + ” many albums \n”;
}

alert(output);
}

displayArtist({

name: “The Flying Robots”,
albums: 250
});

displayArtist({
name: “Schrodinger’s Kittens”
});

It’s nice to see how an object literal ({ //stuff };) can be used as a means to neatly pass multiple arguments (**technically it’s just one argument – an object – with multiple properties!) to a function, but it might not be clear that typeof is really necessary.

It’s important to understand that there’s actually only one argument being passed to displayArtist (I didn’t get this until my second read-through). Then, typeof is used to check for the existence of certain properties on that object (name, number of albums). Depending on the existence of those properties and how typeof evaluates them, the if statements correctly append the relevant information to the output string, which displayArtist happily alerts to the screen. This way we have one function, displayArtist, capable of performing one action, displaying artist info. And it does it correctly even when the available artist info might change from case to case.

Of note is that the typeof call returns a string with the type of the thing you passed it (its operand, or what it operates on, get it?), which is why we’re comparing it to “string” or “number” instead of string or number.

2. Bracket notation for properties — we already know how to access object properties with dot notation, like person.name. We can also use bracket notation, where we put the name of the property in quotes inside a bracket, like person[“name”]. This lets us use variables to access properties, like var thisVariable = “name”; person[thisVariable]; will return person.name for us. **Note that when using a variable for a property name, no quotes are placed around the variable’s name.

 

6/29/2014 (Sun)

Continuing with Chapter 5, “Reference Types” of Professional. At first I wasn’t looking forward to this chapter, fearing it was going to be as boring as Chapter 4’s exhaustive discussion of various variables. But – it’s actually really cool!

I’m really digging this fast and loose approach javascript has to types. Want a function? Great, just make it! No need to declare a return type. Want to pass arguments to that function? Great! Pass whatever you want, more than, less than what it was declared with – doesn’t matter! Want an array? Want that array to hold different types of objects? Go ahead! Any slot can hold anything! Need to change that variable from one type to another? Go ahead! We’ve got built in logic to handle type coercion. Seems very cool to me, like the language gets out of my way and just lets me do what I need to do when I need to do it.

I’m excited to see how this freedom feels when I’m actually building a real project. I can see how some might find the lack of structure dangerous, as a possible contributor to sloppy programming, but I’m confident I’ll find it liberating.

What I did:

1. Kept reading Ch. 5, “Reference Types” from Professional

Cool things I learned:

1. Arrays can be of mixed types

 

6/30/2014 (Mon)

Time to crush through Chapter 5 (and hopefully 7) of Professional. I’m glad to be learning as much as I am about javascript “from the ground up,” but I’m beginning to get a bit antsy. I want to build something, and am slightly anxious about learning so much material before integrating it all (what if I forget!). I know the Codecademy stuff gives me an opportunity to do that in chunks, so maybe my anxiety will go down once I get to the next Codecademy module.

I guess part of it is also accepting that I won’t know everything about the language at all points in time. I will probably always have to look things up, and that’s okay. The work now is just to build a really solid foundation so that when I do look things up the cost per look-up is as low as possible. It should be just a matter of going “ah, okay, that makes sense” and moving on with my project.

It’s tough but taking the long view is what will pay off in the end. Time to put it in cruise control and crush some work. **I definitely did more than three hours today – more like five. And in all that time, I only made it through 30 pages of material in Professional. Nonetheless, I know I learned a ton. So it goes!

What I did:

1. Kept reading Ch. 5, “Reference Types” from Professional

Cool things I learned:

1. Arrays are very flexible – multiple types of objects can be held, and arrays will dynamically increase in size if you set a value beyond current length.

var books = Array(“LoTR”, {name: “Gandalf’s Diary”, author: “Gandalf”}, “Bilbo’s Guide to Dragons”);

alert(books.length); //3
books[5] = “Potions, a History”;
alert(books.length); //6

2. array.length is powerful – It’s not a read-only value, you can actually set it.

var books = Array(“LoTR”, {name: “Gandalf’s Diary”, author: “Gandalf”}, “Bilbo’s Guide to Dragons”);

alert(books.length); //3
books.length = 2;
alert(books[2]); //undefined

Here we lopped off the last element of our books array (“Bilbo’s Guide to Dragons”), so when we try to alert it, we get undefined because the array position does not exist. **Note – when an array position does exist, if it has not been filled with a value, it will also return undefined when we try to display it.

3. Is it an array? – According to Zakas this question has been quite vexing for javascript to answer. So vexing that a definitive Array.isArray() method has been created. It appears that instanceof is insufficient because multiple global contexts might exist if two different frames define two different globals. In this case, you might receive an array from the other frame and not be able to determine if it is actually an array, since the constructor responsible for that object would be different.

var flowers = [“tulips”, “roses”, “violets”];
alert(Array.isArray(flowers)); //true

var cars;
alert(Array.isArray(cars)); //false

cars = [];
alert(Array.isArray(cars)); //true

var stores = new Array();
alert(Array.isArray(stores)); //true

I’m not entirely sure how Array.isArray() will be useful for me (kind of like my hesitation with typeof), since if I’ve made an array I should know that it is actually an array. I’m sure this will become clearer once I build a real project and encounter an actual use-case.

4. Printing objects – Once I found out that Arrays can hold multiple types of objects in the same array, I was curious about how to print out an object. The following is the first method I found that works.

var books = [“LoTR”, {
name: “Gandalf’s Diary”,
author: “Gandalf”,
toLocaleString: function(){
return this.name + ” ” + this.author;}}, “Bilbo’s Guide to Dragons”];

alert (books.toLocaleString());

If you try alert(books.toString()); or alert(books.valueOf()); or just alert(books) (which calls .toString() behind the scenes), you always get “[object Object]” instead of “Gandalf’s Diary Gandalf”. It looks like .toLocaleString() was intended as a way to print strings in specific languages using local character sets, but it also offers us an option to define specific display options for objects. Pretty cool!

If you’re interested in printing an object that you haven’t defined a .toLocaleString() method for (say, for debugging purposes) this Stack Overflow page has some suggestions on how others have solved the problem.

5. Undefined or blank array values – Array values that have not had a value assigned return undefined. But, when the array is converted to a separated list of strings, a blank is returned instead (not a blank space – ” ” – but just a blank – “”).

var books = [“LoTR”, “Ye Olde Tome”, “Bilbo’s Guide to Dragons”]; //the array books is made with 3 values

books.length++; //books[3] is added, but is undefined
books[books.length] = “The Final Book”; //books[4] is added as “The Final Book”

alert(books); //a comma separated list of .toString() on each object is given, with an empty space for books[3]
alert(books.join(” AND “)); //here the empty space is more easily visible because the join call uses ” AND ” to join each string, instead of the usual comma

A blank is also returned if the array element’s value is null.

6. How do you sum the digits of a number together? Two things need to happen: 1) Convert each digit in your string (the number) to a variable of type number. 2) Sum the digits.

var userNum = prompt(“Enter a number please”);
var sum = 0;
alert(typeof(userNum)); //it’s a string
for (var i = 0; i < userNum.length; i++){
var tempValue = +userNum[i]; //converts to number
sum += tempValue;
}
alert(sum);

This was a particularly tricky challenge for me. I tried desperately to find out if prompt(); returned a string or a number by using the isNaN() function. Little did I know, isNaN coerces non-numeric values to number. If I type 1234 in the prompt, it is a number according to !isNaN. If I type “1234” in the prompt, suddenly it is not a number according to !isNaN.

Using typeof instead gave me a non-coerced value for the type of the variable prompt returns. It is a string.

The unary + operator simply makes a number positive. Since the digits of a number are already positive, this does nothing to the sum we want to calculate but does cast the individual digits of our number from strings of length 1 into number variables. Solution found!

This was a good exercise for me to do since it involved independent problem solving without the crutch of the book or Codecademy. It also let me get deeper into type coercion and type casting in javascript, and let me learn that you can kind of** treat strings like arrays.

**However, trying to manipulate userNum.length, or calling userNum.pop() or userNum.push() will not work.

7. Arrays can be Stacks (LIFO) – You can make an array behave like a stack (LIFO queue) by using array.pop() and array.push()array.pop() returns the last item of the array, deletes the item, and decrements array.length by one. array.push(“thing”) pushes “thing” onto the end of the array, increments array.length by one, and returns the new array.length.

8. Arrays can be (FIFO) Queues – You can make an array behave like a queue (FIFO) by using array.shift() and array.push(). Since you want the queue to be first in first out, you need a method for retrieving items from the front of the array. array.shift() returns the first item of the array and decrements array.length by one.

9. Arrays can let you add to the head, and retrieve from the tail – Use array.unshift(“thing1”, “thing2”) to add as many values as you want to the head of the array. Use array.pop() to pop the last array element. array.unshift() returns array.length

Confused about the difference between 7, 8, and 9? Me too, it took a coupe of times to think through it and grasp what was going on. In the LIFO Stack (7), you add (push) and retrieve (pop) elements from the same place – the tail of the queue. In the FIFO Queue (8), you add (push) and retrieve (shift) from different places – the tail and the head of the queue. In 9, you add (unshift) and retrieve (pop) from different places – the head and the tail of the queue, respectively (maybe we could call this a “LILO” queue? I think it’s logically the same as the FIFO queue but I’m not sure…).
10. Sorting arrays – array.reverse() does just what you think it does, but array.sort() is a bit more tricky. First it casts all the array objects to instances of the String constructor by calling String() on them. Then it lexicographically sorts the elements.
This has some weird consequences.

var numberList = [0, 1, 2, 10, 11, 23];
numberList.sort();
alert(numberList); //[0, 1, 10, 11, 2, 23];

You can pass array.sort() a comparison function that will be used to order your array elements. Zakas suggests the following comparison function, which he says will work on most data types.

var numberList = [0, 1, 10, 23, 2, 11]; //out of order this time
numberList.sort(compare);
alert(numberList); //[0, 1, 2, 10, 11, 23];

function compare(value1, value2){
if ( value1 < value2 ){
return -1;
}
else if ( value1 > value2 ){
return 1;
}
else {
return 0;
}
}

Recall that the function compare() can be used before it was declared because it gets hoisted (since it is a function declaration instead of a function expression).

Comparison functions return a negative value if the first element should come prior, 0 if the two elements are equivalent in position, or a positive value if the first element should come after the second.

Also note that array.reverse() and array.sort() return a reference to the array on which they were used. You can verify this yourself by calling alert(typeof array.sort()); //It returns object.

11. The array.concat() method – allows you to append elements or other arrays’ elements to an existing array.

var listOne = [1, 2, 3, 4];
var listTwo = [5, 6, 7];
listOne = listOne.concat(listTwo, [8, 9], [10]);
alert(listOne); //”1,2,3,4,5,6,7,8,9,10″

Calling .concat() on an array without passing any arguments clones the array.

var listOne = [1,2,3];
var listTwo = listOne.concat();
alert(listTwo); //”1,2,3″

**This is important, because if we try to copy an array to a second array variable like we would a primitive variable, the following behavior happens.

var listOne = [1,2,3];
var listTwo = listOne;
alert(listTwo); //”1,2,3″
listTwo.pop();
alert(listOne); //”1,2″

Since arrays are objects, they are reference types. In the example above both listOne and listTwo point to the same space in memory, so editing one results in edits to the other.

var num1 = 5;
var num2 = num1;
num2 -= 1;
alert(num1); //5

As we know, primitive variables do not operate the same way, since they pass by value instead of by reference. If you want to copy an array to a second array, use .concat().

12. Array.slice() – copies a selected portion of an array, and permits counting backwards from array.length value. array.slice(-1) copies the last element in the array. The interval slice copies is closed on the left and open on the right. If only one argument is specified, array.slice() copies every element from that position to the end of the array, inclusive.

var vacationOne = [“Tokyo”, “Yokohama”, “Osaka”, “Kobe”, “Kyoto”];
var vacationTwo = vacationOne.slice(2,3); //[“Osaka”]
var vacationThree = vacationOne.slice(3); //[“Kobe”, “Kyoto”]
var vacationFour = vacationOne.slice(3,2); //empty array
var vacationFive = vacationOne.slice(-3, -1); //from array.length-3 to array.length-1 [“Osaka”, “Kobe”]

13. Array.splice() is super powerful. It can delete, insert, or replace array elements. It takes 3+ arguments. A starting position, the number of elements to delete, and the elements to insert.

var fruitStand = [“apple”, “orange”, “banana”];
fruitStand.splice(1, 0, “pineapple”, “grapefruit”);
alert(fruitStand); //”apple”, “pineapple”, “grapefruit”, “orange”, “banana”

Array.splice() returns the items that were deleted, or an empty array if no items were deleted.

14. Iterative methods on arrays – there are five of them, and they are pretty self-explanatory once you understand what’s going on. Basically, these are methods that will iterate through every value on the array and perform some function. The method takes two arguments: the function, and an optional scope variable (which specifies what this. refers to). The function that the method takes receives three arguments (you don’t need to pass them to it, it already gets them): item, index, and array. This is the item at the given index in the array we’re analyzing.

var favNums = [23, 45, 68];

//every, filter, forEach, map, some

var everyTest = favNums.every(function(item, index, array){
return (item > 21);
});

alert(everyTest); //true

var filterTest = favNums.filter(function(item, index, array){
return (item > 46);
});

alert(filterTest); //array containing 68

var eachTest = favNums.forEach(function(item, index, array){
if ( !isNaN(item) ) {
console.log(“Position ” + index + ” is a number!\n”);
}
});

var mapTest = favNums.map(function(item, index, array){
return ++item;
});
alert(mapTest); //[24, 46, 69]

var someTest = favNums.some(function(item, index, array){
return (item > 69);
});
alert(someTest); //false – would have been true if at least one item had passed the condition

Interestingly, if we return item++in our mapTest() function, we get [23, 45, 68]. I think this is because the postfix increment operator gets evaluated after the return passes the current values along. Since mapTest() is generating its own array to return, the actual values in favNums remain unchanged. So there’s no way to access the incremented values without making it a prefix operator like we did here, or writing return item += 1;.

15. Date trickery – The Date() type is quite tricky. For example, var y2k = new Date(2000, 0) should return midnight on January 1st, 2000 (the months are zero-indexed, and the first argument is the year). On my Fiddle it returned “December 31, 1999 19:00:00”. That’s because it returns the date in the local timezone, which happens to be GMT – 5.

There’s a lot of nuance for Date.parse(), Date.UTC(), Date(), and the various input syntaxes, but those can safely be left for individual lookup. A much cooler use is,

var start = +new Date();

//code you want to time

var stop = +new Date();

result = stop – start;

Looks like a sweet way to optimize runtimes. Also cool to note that you can place the unary + operator in front of the new and it still works. You can replace the unary conversion of new Date objects to numbers with var start = Date.now(); in ECMAScript 5.

16. Regular Expressions (regexp) look powerful as hell. They’re basically advanced ways of doing ctrl + f on a document. They look like this: var pattern1 = /[bj]ob/gmi;

Here pattern1 will be used to look for all instances of “bob” or “job” in a case-insensitive fashion (so “bOb” will also be returned, e.g.) in multiline mode (we will continue searching after we encounter the end of a line).

The last characters, m and i, are flags. There are three: g (global – the pattern applies to all of a string rather than stopping after the first instance is found), m (multiline mode, as explained above), i (case insensitive mode).

There are special characters called “meta characters” in regexps, like the [bj] in our example above. If you want to actually search for a ‘[‘ or a ‘]’ you have to escape the character like so: var pattern2 = /\[bj\]ob/mi;

This pattern will search for instances of “[bj]ob” in a case-insensitive, global, multiline mode. Another useful meta-character is the period. var pattern3 = /.ly/gi; will search for all three-letter words ending in ly (with the global and case-insensitive flags applied).

var re = /cat/g;
var matches = re.exec(“catastrophe”);
alert(matches[0]); //”cat”

alert(matches.index); and alert(matches.input); give 0 and catastrophe, respectively. They display the index at which a hit was found, and the original input string.

If the regexp is in /g mode, it will continue to search from the last index value it found a hit at each subsequent time the regexp.exe() is called. Otherwise, if run again it will simply start from index 0 again.

var re = /cat/g;
var query = “catastrophecat”;
var matches = re.exec(query);
alert(matches.index); //0
matches = re.exec(query);
alert(matches.index); //11

**Validating user input in forms, etc: Perhaps the most immediately useful regexp property is .test(). Running pattern.test(“string”); returns true if the pattern is present in the string, and false otherwise.

I’m confident this is just the tip of the iceberg as concerns regexps, and I’m sure they can get much more convoluted. For now though this is where I’ll leave them be.

 

07/01/2014 (Tues)

Wow, it just keeps getting thicker the farther you go! Spent a good amount of time reviewing my notes from yesterday. I know it helped increase retention, and I found a couple small errors, but it was a time consuming affair. I’m trying to find a good balance between learning deeply and moving quickly.

For today I want to finish Chapter 5 of Professional and take a look at some CSS just to refresh my brain on how it looks. If I have time I’ll move on to Chapter 7, “Function Expressions.”

I think I’m going to try reading for longer chunks and summarizing more aggressively when I write my notes. Right now I’m basically writing down at a 1:1 ratio – learn a concept, write it down. I’ll try reading longer sections and then writing down briefer summaries to increase my speed moving through the text.

What I did:

1. Continued Ch. 5, “Reference Types” of Professional.

Cool things I learned:

1. Functions are objects, so their variables are actually reference variables containing a pointer to the object.

var combinator = function(thing1, thing2){
alert(thing1 + thing2);
};

combinator(“air”, “bud”); //”airbud”
var copycat = combinator;
copycat(“copy”, “cat”); //”copycat”
combinator = null; //dereferences combinator
copycat(“Don’t stop “, “believing”); //hold on to that feeling

Even though we dereference combinator()copycat() still points to the function and executes correctly. This example also works if we use a function declaration instead of a function expression to define combinator().

2. Functions are objects, so they can be passed like objects. You can use one function to call another function.

function callsAnother(someOther, anArg){
return someOther(anArg);
}
function someOther(anArg){
return ++anArg;
}
alert(callsAnother(someOther, 5)); //6

You can also return functions, just like a regular function would return some variable or computation. Let’s say you want to sort an array of objects, but those objects have several properties and you only want to sort on one of them. Recall that the array.sort(compare) method takes a comparison function (here called compare), which itself takes two values: compare(value1, value2), the values to compare. You don’t have a way of selecting which object property you want to sort on!

Consider the following.

var bookShelf = [{name: “The Wizard’s Almanac”, author: “Gandalf”}, {name: “Bilbo’s Guide to Botany”, author: “Bilbo”}, {name: “High Elf Fashion, a Retrospective”, author: “A. Legalos”}];

function makeComparer(objectProperty){
return function(object1, object2){
var value1 = object1[objectProperty];
var value2 = object2[objectProperty];

if (value1 < value2){
return -1;
}
else if (value1 > value2){
return 1;
}
else {
return 0;
}
}
}

alert(bookShelf[0].name);
bookShelf.sort(makeComparer(“name”));
alert(bookShelf[0].name);
bookShelf.sort(makeComparer(“author”));
alert(bookShelf[0].name);

Our first alert() returns “The Wizard’s Almanac.” The second returns “Bilbo’s Guide to Botany,” and the third “High Elf Fashion, a Retrospective.” Note the bracket notation used in the function makeComparer() returns, which allows us to access properties via variables (unlike the dot notation we use in the alert()‘s later on).

It was interesting to see that the object properties we’re interested in must be passed in as strings. Just typing name instead of “name” would not work.

3. Recursive calls to functions can be implemented with arguments.callee(), though this does not work in strict mode.

function factorial (num){

if (num <= 1) {

return 1;

}

else{

return num * factorial (num-1);

}

}

Rewritten using arguments.callee() the else block looks like this:

else {

return num * arguments.callee(num-1);

}

In this case, if the function pointer factorial were to be changed (say, dereferenced), but you still had another pointer pointing to the same place (say, factorial2), then factorial2 would operate correctly in the arguments.callee() example, but incorrectly in the previous example. arguments.callee() lets you decouple recursive function calls from the function name.

4. The this keyword refers to the current object of scope.

window.color = “green”;
var o = { color: “blue” };
function sayColor(){
alert(this.color);
}
sayColor(); //green
o.sayColor = sayColor;
o.sayColor(); //blue

Note that the line o.sayColor = sayColor; accesses the function pointer sayColor instead of calling the actual function sayColor(). Writing o.sayColor = sayColor(); would have assigned whatever the function sayColor() returns to be the value of the property sayColor on o.

5. The functionName.caller property returns the source code of the function responsible for calling functionName(). If functionName() is a global function and is called from the global space, the entire source code is returned, wrapped in an anonymous function(), which is pretty interesting. Perhaps that’s how javascript runs all the time, with this anonymous function() containing the entire global space.

6. The .call() property allows you to define what this means for the function you are calling. Instead of defining another function pointer as a property on the object, we can just pass the object as the this in .call().

So returning to our window.color and o example from #3, we can just write sayColor.call(o); and get “blue” in return. This way, the object whose this we want to use doesn’t have to know anything about the method we are using on it.

 

7/02/2014 (Wed)

Going to try and power through the rest of Chapter 5 today. At 70 pages it’s a beast, definitely one of the longer ones in Professional. I’ll try implementing some more speed tricks to move through the material quicker.

What I did:

1. Read the summary of Ch. 5 of Professional to get an idea of what the main points are in the chapter, so I can focus my reading for the rest of the chapter.

2. Finished reading Ch. 5.

3. Fixed a CSS issue to brighten the unvisited link color on another website of mine. (Something I had asked the dev I was working with to do, but he never got around to. Now I can fix it myself!)

4. Continued Codecademy Javascript track with Section 6, “Data Structures.”

Cool things I learned:

1. How to actually cast variables! – Finally, I learned how to actually do this without calling some random operator like unary +.

var s2 = “25”;
alert(typeof s2); //string
var s3 = Number(s2);
alert(s3 instanceof Number); //false
alert(typeof s3); //number

Just use the primitive value wrapper types Number, Boolean, and String to cast your variables appropriately.

2. Strings have several methods available for use on them. .indexOf(“substring”, startPos) and .lastIndexOf(“substring”, startPos) do exactly what you would expect from the Array examples. .charAt(pos) and .charCodeAt(pos) also do what you think. As previously mentioned, bracket notation can reference a character at a specific position in a string, and can accept variables. .slice(), .substr(), and .substring() all do fairly similar things, and can be looked up if more is needed.

var text = “Lorem ipsum dolor sit amet, consectetur adipisicing elit”,
pos = text.indexOf(“o”),
positions = new Array();

while (pos > -1) {
positions.push(pos);
pos = text.indexOf(“o”, pos + 1);
}
alert(positions); //1,13,15,29

var text2 = “stuff”;
var thing = 1;
alert (text2[thing]); //”t”

The .trim() method also seems very useful, removing all whitespace around the string. Since .trim() creates a copy of the string it is called on, it must be explicitly saved or the original string remains unmodified.

3. Using .apply() with the Math singleton object. You have two singleton objects, global and Math. In practice global is window in browsers, but we’ll learn more about that when we do the DOM. Math lets you do a bunch of useful math stuff (rounding, the value of e, etc.).

var values = [45, 46, 47, 342432];
var min = Math.min.apply(Math, values);
alert(min);

Similarly to .call().apply() sets the value of this with its first argument. With its second argument, it passes an argument or an array of arguments. Here we use .apply() to set this equal to the Math singleton object, and apply it to each of the values in the values array. With .call() we attached .call() to the end of a function and included the reference value (object) as an argument, thereby setting the value of this.

It turns out for the Math object it really doesn’t matter what we set this to. Setting it to null or even undefined or “foobar” all work, since Math.min() and Math.max() don’t use this. It’s just a hack to get them to accept an array of arguments, since .apply() can accept arrays of arguments.

4. Math.random() can be useful for selecting from among choices, when combined with Math.floor(). Say I had three different headlines and I wanted one to display randomly when a user loaded my page. I might calculate the numerical portion of a CSS id (say, the 1 in #headline1) as follows.

var choice = Math.floor(Math.random() * 3 + 1));

The Math.floor() takes the mathematical floor of the number (cuts off the decimal points), and Math.random() generates a random decimal between (0, 1), so zero and one are not included.

 

7/03/2014 (Thurs)

What I did:

1. Finished Codecademy Section 6, “Data Structures” of Javascript track

Cool things I learned:

1. You  have to provide the full naming hierarchy for the object you are manipulating despite being inside a for/in loop that is already inside part of that hierarchy. I think what I’m saying will become clearer when we consider the following example from Codecademy.

var friends = {
bill: {
firstName: “Bill”,
lastName: “jackson”,
number: “123”,
address: [“Place”, “place”, “place”]
},
steve: {
firstName: “Steve”,
lastName: “mandrake”,
number: “456”,
address: [“Place”, “place”, “place”]
}
};

function list(obj){
for (var key in obj){
console.log(key);
}
}

function search(name){
for (var key in friends){
if ( friends[key].firstName === name) {
console.log(friends[key].firstName, friends[key].lastName, friends[key].number, friends[key].address);
return friends[key];
}
}
}

Inside the function search(name) we’re looking to see if the name passed to search() matches any of the firstName properties of any of the objects that are inside the object friends. Despite the fact that our for/in loop already specifies the fact that we are concerned with keys inside the object friends, our if statement on the next line has to specify friends[key].firstName, instead of just saying [key].firstName.

Interestingly, trying this[key].firstName does not work either. Which makes sense, since this in the context of search() is the execution context of the function search(). If my understanding of the scope chain is correct, javascript should look for the key in the current execution context, not find it, and then search for it in the global context. But I suppose since the key isn’t tied to an object, javascript doesn’t know what object to look for the key in. I suppose it shouldn’t assume the key is in the object manipulated by for/in since we might be comparing matches across different kinds of objects.

 

7/07/2014 (Mon)

Hope everybody had a great Fourth of July weekend! After visiting my parents I’m ready to tackle javascript again. I’ve realized two important things. First, trying to do everything at once will result in failure. It’s okay to take things a little bit more slowly, you’ll still make it across the finish line. Second, I may not be successful. That’s okay, and you have to find some way to make the process enjoyable, because the outcome is not guaranteed — but the process is.

What I did:

1. Reviewed my notes from Thursday and continued Codecademy’s javascript track with “Introduction to Objects” from section Objects I. Still have Objects II to do before moving on to the 5 Basic Projects on the Basic Projects track.

Cool things I learned:

1. Setting an object’s prototype is as simple as Penguin.prototype = new Animal();. An object inherits, in hierarchical order, all the properties and methods up the prototype chain.

2. Getting absorbed in petty Stack Overflow downvotes/mean comments is unproductive and ruins your time. Only ask a question if you really really cannot find the answer. Even then, be prepared for dicks to try and ruin your day and keep it moving if said dicks are encountered.

3. Using the developer’s console of your browser (Chrome, Firefox) will reveal errors to you that JSFiddle and Codecademy’s compilers will not. Use this when you have code that won’t work and you don’t know why!

 

7/08/2014 (Tues)

It’s quite confusing to keep seeing Codecademy call objects “classes.” I understand they are trying to impart some wisdom about object oriented programming, but Zakas specifically refuses to call javascript objects classes, so it is confusing to see the terminology adopted here. It causes this little mental glitch each time I read it where I have to correct the text in my head.

What I did:

1. Reviewed my notes from 7/02/2014 (Wed). Was good to refresh my memory!

2. Reviewed some Codecademy exercises from Introduction to Objects II that I glossed over last time.

3. Finished Codecademy’s Javascript track!

4. Reviewed three interesting questions on the subreddit for learnjavascript. The last question in particular has excellent responses by user _bilbo.

5. Started reading the DOM chapters in Professional, beginning with Chapter 8, “The Browser Object Model.”

Cool things I learned:

1. Objects have public and private properties and methods – public properties and methods are always set using this inside a constructor. For example

function Book(title, author){

this.title = title; // all book objects’ titles will be public

this.author = author; // all book objects’ authors will be public

}

2. To make the property or method private, simply set it using var inside your constructor. Attempts to access it will result in undefined being returned.

function Book(title, author, rating){

this.title = title; //public

this.author = author; //public

var myRating = rating; //private

var myFunction = function(){

//do something

};

}

3. Private properties can be accessed with public methods, which seems somewhat similar to the getter and setter accessor methods we studied earlier (see 6/26/2014, number 5 on things I learned). In your constructor, simply use this to declare your public method, as follows.

function Book(title, author, rating){

this.title = title; //public

this.author = author; //public

var myRating = rating; //private

this.showRating = function(){

return myRating;

};

}

4. What about the combination constructor/prototype pattern we were using earlier? Recall that we split properties into the constructor, and methods into the prototype in order to avoid duplicate function instances for each object the constructor creates, while still having a unified place that’s not in the global space where all of a given object’s methods live. Can that approach be applied to private variables?

function Person(name, balance){
this.name = name;
var balance = balance;
}

Person.prototype = {
constructor: Person,
getBalance: function(){
alert(this.name + ” has a bank balance of ” + this.balance);
}
}

var john = new Person(“john”, 345);
john.getBalance();

Running this code prints “John has a bank balance of undefined.” If we change the prototype’s alert statement to alert(this.name + ” has a bank balance of ” + balance); we get Reference error: balance is not defined. I thought that might work since we declare balance as var balance inside our constructor, instead of as this.balance, but it did not.

When googling for the solution, Richard’s post “OOP in JavaScript: What you NEED to know” came up as the first hit, and it’s something scheduled for reading in Weeks 7 and 8. I’m not sure if I’m going to wait to finish the whole course before jumping in to coding Mamoru, but I might make a special detour to read this post!

5. Though I really don’t know why anyone would do this, it’s possible to make a private method and use a public method to return that private method.

function Book(title, author, rating){

this.title = title; //public

this.author = author; //public

var myRating = rating; //private

var showRating = function(){

return myRating;

};

this.lookAtRating = function(){

return showRating;

}

}

Notice that showRating() is a private function, and lookAtRating() is public. lookAtRating() returns showRating. Notice that there are no parentheses after showRating in the return statement. This is because we want a pointer to the function to be returned, not the result of calling the function. The parentheses transform the pointer to the function into a call to that function.

Outside of your object, say with the book Twilight, you could then write var getSomeRating = Twilight.lookAtRating(); var twiRating = getSomeRating();

6. You can use a private property coupled with a public method to enforce password-protected access to a resource. For example,

function Person(name, balance){

this.name = name;

var bankBalance = balance;

this.askTeller = function(pass){

if (pass === “1234”){

return bankBalance;

}

else {

return “Wrong password”;

}

}

7. To extend the prototype by adding a method to a given object, do the following.

function Dog (breed) {
this.breed = breed;
};

// add the sayHello method to the Dog class
// so all dogs now can say hello
Dog.prototype.sayHello = function() {
console.log(“Hello this is a ” + this.breed + ” dog”);
};

var yourDog = new Dog(“golden retriever”);
yourDog.sayHello();

var myDog = new Dog(“dachshund”);
myDog.sayHello();

8. hasOwnProperty(“property”) is useful. You want to check if an object has a certain property. Simply do object.hasOwnProperty(“propertyName”). It returns true or false. We learned that all objects have access to the hasOwnProperty() method because they inherit it from Object.prototype. As you might expect, the following evaluates to trueObject.prototype.hasOwnProperty(“hasOwnProperty”);

9. Private properties are not accessible from a for/in loop that is external to the object.

function StudentReport() {

var grade1 = 4;

var grade2 = 2;

var grade3 = 1;

this.getGPA = function() {

return (grade1 + grade2 + grade3) / 3; };

}

var myStudentReport = new StudentReport();

for(var x in myStudentReport) {

console.log(x + ” is a ” + typeof myStudentReport[x]);

}

Running this code logs the following message to the console: getGPA is a function. The grade variables are no longer accessible as properties on the object myStudentReport.

10. The window vs. Global – In the Browser Object Model (BOM), the window is javascript’s Global. However, variables declared in the global space have their [[Configurable]] property set to false, and so delete window.variable will not work and return false. However, if the variable is explicitly declared as a property on window as in window.color = “red”; then delete window.variable will work and return true.

11. Evidently every HTML <frame> has its own window object, which is its own window. To get to the outermost window, which is the browser window, use top.

 

7/09/2014 Wed

My goal for this week is to get to a point where late this week or next week I can build the quiz application. Once I’m done with the quiz application I want to start building Mamoru.

This will be my 9th day spent on “Weeks 3 and 4” of Learning Javascript Properly. I do not think today and tomorrow gives me enough time to finish the syllabus for these two weeks in its entirety. I think these weeks are substantially meatier than is thought, but I’m not going to worry about it. I just need to do what I need to do to get to where I want to be.

A New Approach: since Chapter 8 proved to be mostly useless for my purposes, from now on I’m going to read the chapter summary first before deciding whether or not to read the whole chapter.

The assigned chapters were: 8-11, 13 and 14.

I scanned 8, and will read: 10, 11, 13 (sections on device events, and more general things like event delegation), 14 (sections to be determined).

I will skip 9 in full, and portions of 13 and 14 as necessary.

Chapter 10 “The Document Object Model” turned out to be highly unintelligible. I’m going to read Chapter 15, “Scripting Documents” from JavaScript: The Definitive Guide instead.

What I did:

1. Reviewed yesterday’s notes and my notes from 7/01/2014 (Tues). I find I quite enjoy reviewing notes in pairs like this. Yesterday’s notes keep me focused on what I need to do today, and notes from some time ago increase retention. I find myself going “Ohh yeah, I remember that!..”

2. Finished reading Ch. 8, “The Browser Object Model” from Professional, but found myself skipping most of it, since it has to do with opening new windows or resizing existing ones, browser history, etc. – things that are irrelevant for a single-window, full screen app.

3. Read up on try/catch blocks and why they’re not used in javascript (performance hit due to dynamic scoping).

4. Decided that Chapter 10 “The Document Object Model” of Professional was too unintelligible to be useful. I’m going to read Chapter 15, “Scripting Documents” from JavaScript: The Definitive Guide instead, and may sub out some more chapters as I go on.

Cool things I learned:

1. Everything about CSS and browser properties is all f$@#’d up. The first few parts of Chapter 8 just keep saying “here’s a property, and there’s no consistent way to get at it across browsers.”

2. There is an interesting article over at Quirksmode about the two different viewports for mobile: the layout viewport (which acts like the desktop viewport, basically, and is fixed) and the visual viewport (which can change in size and orientation). This distinction seems really helpful for thinking through mobile web design.

3. setTimeout() and setInterval() seem like they could be useful for Mamoru’s design, since I need the client to take action as the timer approaches zero (i.e. a reminder alert at t-minus one minute). But I have a feeling that there’s probably a built in method somewhere to run a timer, and using that will probably be more straightforward than building my own loop.

4. Evidently setInterval() is avoided because the time between intervals is not guaranteed. Instead, we can set an interval like this.

var num = 0;
var max = 0;

var waitTime = prompt(“Enter a time in seconds to wait”);

waitTime *= 1000;
max = waitTime/500;

function incrementNumber(){
num++;

if (num < max) {
setTimeout(incrementNumber, 500);
}
else{
alert(“Done”);
}
}

setTimeout(incrementNumber, 500);

This code asks the user for a number of seconds to wait, and then chops that time up into 500ms chunks. Each chunk corresponds to a single unit increase in the counter variable num. Once num equals the total number of chunks the user asked for, the alert executes.

Notice that setTimeout() calls incrementNumber without any parentheses. Calling it with parentheses inside the loop makes the “Done” statement appear without waiting for the interval to actually expire. I think this is because the setTimeout call is actually executing on the result of the function incrementNumber when parentheses are included.

5. HTML5 has <section>, <article>, <footer>, <header>, and <nav> tags. All of these are like specialized <div> tags to help you style your page. I hadn’t encountered these anywhere until someone mentioned them in the learn javascript webchat. Good to know what’s out there, especially since the Codecademy basic web design track (HTML + CSS) did not cover these.

6. p. 256 of Professional has a really great example of ternary conditional operators, loops, .split(), and arrays to scrub query strings from the page URL using the window.location property (equivalent to document.location).

function getQueryStringArgs(){

//get query string without the initial question mark

var qs = (location.search.length > 0 ?     location.search.substring(1) : “”),

//object to hold data

args = {},

//get individual items

items = qs.length ? qs.split(“&”) : [],

item = null,

name = null,

value = null,

//used in for loop i = 0,

len = items.length; //end var declarations

//assign each item onto the args object

for (i=0; i < len; i++){

item = items[i].split(“=”);

name = decodeURIComponent(item[0]); value =         decodeURIComponent(item[1]);

if (name.length) {

args[name] = value;

}

}

return args;

}

07/10/2014 (Thurs)

I can see the light at the end of the tunnel! My time with Richard’s How to Learn Javascript Properly is coming to a close, and I’ll be branching off into what I need to do to build Mamoru. Exciting times ahead!

What I did:

1. Checked out an interesting question on the learnjavascript subreddit. Looks like making a simple Chrome extension might not be that hard after all!

2. Made some higher-level decisions about how to proceed: AngularJS instead of JQuery, Ionic on top of Cordova, and Node.js + Heroku for the backend. Thinking about collecting all this into a mega-post that would basically outline a new syllabus so that people in my position could just follow it instead of having to cobble things together like me.

3. Made some immediate decisions about how to proceed now: read the JavaScript: The Definitive Guide chapters on the DOM instead of the Professional chapters. They’re more teaching focused and less like a reference manual. Here’s my immediate todo for the foreseeable future.

  1. Read Ch. 15 “Scripting Documents”
  2. Do the 5 Basic Projects at Codecademy
  3. Read Stubbornella’s Guide to CSS
  4. Finish the remaining chapter readings
  5. Read Richard’s “OOP in JavaScript: What you NEED to know” post
  6. Do the quiz assignment
  7. Read  “Anatomy of a Typical Modern JavaScript App” from Programming Javascript Applications
  8. Do Code School’s AngularJS course
  9. Determine selections to read from “A Better Way to Learn AngularJS” 

After that, it’s on to learning more AngularJS and SASS as needed while using Iconic to build Mamoru’s frontend, learning the backend (Node.js + Heroku), and deploying to the app stores!

4. Reviewed my HTML + CSS work from the beginning, including some of the codecademy work I had done in the Web Fundamentals track

5. Did the first Basic Project on the Web Projects codecademy site

6. Began reading Ch. 15 of Definitive, “Scripting Documents”

Cool things I learned:

1. Use em (and percent for the <body> element’s font-size), not px, for font sizes, and percentages, not px, for <div> widths. This way they scale appropriately when a user zooms in or views the content on a different device. With mobile in mind, the <body> element should set its font-size using a %, and the rest can be set using em.

 

7/11/2014 (Fri)

What I did:

1. Began reading the first reading listed in “A Better Way to Learn AngularJS” , and have realized that reading from this guide first, and then doing the Code School AngularJS course exercises is the way to go. I think the “Better Way” guide may prove especially fruitful, as it says it is designed to teach how to build Single Page Applications (SPA’s), which is what Mamoru will be.

2. Wrote a Stack Overflow answer for how to create an invisible click area that is larger than the size of a button. At first I thought this was for nefarious reasons, but it was actually to increase the clickable area for an “X” to close a popup! Good chance for me to stretch my CSS skills a bit.

3. Continued reading Ch. 15, “Scripting Documents” of Definitive

4. Wrote a Stack Overflow question about a getElementById() example from p. 365 of Definitive. I’m not sure what kind of object elements is, though it appears to be a <key, value> pair where the key’s are element id’s and the values are the elements. But, I don’t really know what it means for a value to be an element. Is it “Object HTMLDivElement” or is it the text inside the div? — Some time later, I came up with my own answer thanks to the Mozilla Developer Network documentation.

Cool things I learned:

1. Angular has things called “expressions” and “filters”. They look like {{qty * cost | currency}}. The qty * cost is an expression, where qty and cost are part of the model, where variables live. currency is a filter, which is an instruction on how to render the output (in this case,  make it look like a currency).

 

bobo

 

Leave a Reply

Your email address will not be published. Required fields are marked *