Zero to One: Building Mamoru – Weeks 1 and 2

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

While winning the Hackathon was great, I’m excited to make Mamoru into my first serious attempt at a company. No doubt the fastest route to market would be hiring a competent programmer to do the heavy lifting for me.

Especially with competitors like Kitestring already live and getting good press, the pressure is high. But I’m taking the long view. Mamoru is not the only company I will build in my lifetime, and the skills and independence I gain now will pay me back tenfold in the years to come.

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.

My strategy is to spend three hours a day working on Mamoru. Sometimes I spend more, and occasionally less. I usually take the weekend off. This is a schedule that works for me.

Despite (in fact, because) of the total naïveté this shows, I am reproducing my original plan for coding Mamoru:

Mamoru Attack Plan

 

1. Go through this JavaScript is sexy tutorial – http://javascriptissexy.com/how-to-learn-javascript-properly/

2. If needed use Eloquent JavaScript as a reference – http://eloquentjavascript.net/contents.html

3. Program Mamoru

I quickly learned it would not be so simple, and this blog series is my story of getting from zero to one.

LJSP: Weeks 1 and 2

The curriculum for Weeks 1 and 2 took me roughly six and a half days. It started with a thorough review of HTML and CSS, which is where I learned about CSS for the first time. The Codecademy course on Web Fundamentals was really well done. I have to say the single most helpful tip Richard (from javascriptissexy.com, where this tutorial comes from) gives, is to try things out on your own. For CSS, playing with the Google Dev Tools panel on various websites was very helpful. It helps to find a simple one (like an academic department’s webpage) instead of a complex one.

In addition to CSS I got deep into the beginnings of javascript. In brief I learned about execution context (scope), functions, variable types, the difference between === and ==, and a host of other important things. I’ve pulled out the most interesting Stack Overflow questions and other resources I encountered at the top, and I’ve included each day’s notes below. Enjoy!

Links for LJSP Weeks 1 and 2:

Stack Overflow Questions

1. My very first question! – I learn about the two elements of an HTML page that never disappear.

2. My second question – on CSS positioning yielded mostly unhelpful answers, mainly because I wrote a poor question. I don’t actually get to what I’m asking until the very end, and the whole thing needs a rewrite. Your question must either be very short or very logical. It cannot meander!

3. A handy CSS width trick – how to use percentages and pixels together to calculate the width of an element.

4. === vs. == in javascript – short answer: always use !== and === unless you have an explicit reason for the type conversion of == and !=.

5. Learning about operators – I ask a question about dynamic properties of primitive variables (which don’t exist in javascript), I get an answer that helps me learn something completely different (what the & , and = operators do).

6. The Stack vs. The Heap – learned about scope and how it relates to memory management within an application and between an application and the OS.

7. The arguments[] object – discovered that arguments[] (a local object containing the arguments passed to a function) is not dynamically linked when “use strict” is enabled. Originally I wanted to ask this question myself, but StackOverflow suggested a previously asked question that was exactly the same!

8. Function declarations vs. expressions – the textbook and Codecademy used different syntax for functions. Turns out each has its uses, though right now I am partial to the declaration, since it actually names your function!

9. When to use var – always, unless you know you want a global variable. This is one of many niceties I would not have internalized unless I had been using JSFiddle to try out each piece of code I saw in the textbook!

10. Function hoisting – declared functions get loaded before any code gets executed. Anonymous functions (ones built as a function expression, e.g. var addNumbers = function(a, b){ //code };) do not.

Resources

0. JSFiddle – really great tool for trying out javascript. Since console.log() won’t write anywhere, just use document.write(). It’ll complain about it, but it worked for me! Also the CTRL + Enter shortcut to execute your code is a lifesaver.

1. SuperheroJS – collection of good articles on javascript. Bookmarked for future reading, but have not consulted since.

2. LearnJavaScript IRC – web-based IRC (chat) client for the “learnjavascript” subreddit, where people are following Richard’s syllabus. Have been using daily. Good to have some community while you code, but don’t get distracted!

3. Dan Moore on Cordova Hooks – an interesting read on the utility of buildtime scripts, but a bit beyond my level right now. Maybe I will understand more fully once I begin building with Cordova.

4. CodeSpaces.com shutters after 7 years – great article differentiating between resilience and a true backup.

5. The Errata for Professional Javascript for Web Developers, 3rd ed.

6. The Morgue File – free, no credit stock photography!

06/17/2014 (Tuesday)

Really glad I’ve decided to work in 3 hour blocks. It’s impossible to get anything substantial done in programming in less time, I feel. Plus the first hour or so was just figuring out where I was in the process, what my next steps were, and what resources to use (from the veritable sea of infinite resources available…).

What I did:

1. Setup a private git repository for my project

2. Install cordova

3. Figure out that cordova and phonegap are basically the same thing, despite the confusing and arbitrary change between using phonegap and cordova as the CLI command in the documentation from 3.0 to 3.5.

4. Figure out how to update all the packages that npm is managing now, and update them

5. Realize I need to spend some time learning just JavaScript and HTML/CSS to begin working on my mobile project, google for tutorials and settle on the JavaScript is Sexy tutorial.

6. Start doing CodeAcademy HTML/CSS (Web Fundamentals) to see what’s changed since 1990 when I was doing HTML last.

7. Learned about tables, <tr>’s have <td> inside them, <th> also exist (what do they do?) and there’s table <title>…

 

06/18/2014 (Wed)

What I did:

1. Continued Code Academy Web Fundamentals, doing CSS

– it’s super important to explore and tinker around with the code yourself. They key trait you want to exhibit: curiosity. This is how you learn. If you just follow instructions you will become an expert instruction-follower, not a coder. A coder is someone capable of transforming ideas into reality, and that requires figuring out how to execute without instructions.

-a lot of it is annoying, for example learning how to type comments, or the introduction to hexadecimal values for colors. i see the value for those completely new to computers, and it doesn’t take too much time to speed through the fluff, so overall worth it, but still a bit of a drag.

2. Found http://superherojs.com/ (collection of good articles on JavaScript) and http://webchat.freenode.net/?channels=learnjavascript (IRC for learnjavascript, gives you the potential to listen to more experienced people talk about javascript) through the Learn Javascript subreddit (which has study groups for Learn Javascript Properly, which seem fairly active though not that large)

3. Read the guest post by Dan Moore on DevGirl (http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/) about three hooks to use with cordova. Hooks are scripts that run during buildtime to automate processes for you. Sounds like they will be helpful, though I’m a bit confused about why they are needed for plugins, shouldn’t cordova be handling that on its own? Probably has to do with setting up different devs’ boxes.

Things I learned that were cool:

1. using px for font size assumes the viewer’s screen is the same as yours. use em instead for a size relative to their screen, helpful when designing something that will be seen on different form factors (i.e., anything these days). 1 em = 1 unit of default text size, relative to whatever the system (browser) has set as default. 2 em = 2 units etc. **Technically, em is relative to the parent element’s font-size, and rem is relative to the root (html) font-size.

2. Default font options (regardless of user’s system) are serif, sans-serif, and cursive. You can also specify a ranked set of fonts in font-family, which will be tried in order.

3. <thead> <th colspan=”3″> </th> </thead> — <thead> is actually a useful tag because it allows you to specify a table title in the <th> tag. Styling to the table applies to the actual container of the table element around the cells. The table is more than its cells, but it doesn’t become apparent until you add a border to the table and the cells and see the difference. I’m beginning to learn that CSS really marries to HTML in a very specific way. HTML is describing the logical hierarchy of containers, like those stacking Russian dolls, and CSS is applying styles to various containers.

4. Simple changes to the <a> selector’s properties in your CSS stylesheet can make things look really nice, instead of the boring blue underlining. Changing the color to #cc0000 and text-decoration: none looked really cool to me. It seems like even simple CSS rules can be very powerful if they were combined artfully.

5. border-radius is my new favorite property! This is how they make the buttons look rounded and cool. border-radius: 5px makes for rounded edges. border-radius: 100px makes an oval button! I always wondered how they did this, border-radius is my new best friend!

Thing I learned that was awful:

1. I learn about CodeSpaces.com shutdown due to an extortionist. Almost all their backups are deleted. Tim Anderson has a good, quick post emphasizing the difference between resilience and backup. I make a mental note to have backups that are behind a different password (seems obvious, but look how seven years just went down the drain). Awful. I hope the criminal gets caught and justice served. I wonder – can you have insurance for that?

What I want to do:

1. Read the source code for something else written in javascript and understand it. Eventually the “q libraries source code” mentioned here and here seems like it would be fun, but it may be outside the scope of what’s necessary for me to get Mamoru working.

 

06/19/2014 (Thurs)

What I did:

1. Finished Code Academy Web Fundamentals, hoping to finish today. I had four modules left, in two groups. The last two groups of CSS.

2. I gotta say I didn’t put much effort into the Build a Resume project at the end of the CSS track. It’s actually quite hard, and I think what it revealed is a lack of clear instruction on positioning. Static, fixed, absolute, relative. They seem very important but not clearly explained. The following StackOverflow questions were instructive though:

Good to know that taking an element out of the flow means its size changes now with respect to its content, not to the element containing it.

I’m still not clear on how to use positioning and the z-index, both of which seem important. Hopefully I will work these things out soon, but for now I’m really looking forward to moving on to javascript tomorrow!

A very cool resource:

1. The Morgue File – great resource of high quality stock photography available for free, no credit usage. This looks more promising than my usual Flickr creative commons search!

Things I learned that were cool:

1. If you want to select a specific HTML tag that is nested within other tags in your stylesheet, you do it like this.

<div>

<div>

<p> stuff i want to select </p></div></div>

corresponds to

div div p {

}

Pretty neat that CSS can wed so tightly to HTML’s native structure like that. I can see that being immensely powerful if you get good enough at this skillset. This property of more specific selections’ rules being prioritized over more general selections is why we call CSS “cascading” style sheets. This is the cascade!

Interestingly enough, in your CSS file you don’t have to do

html body div div p {

}

though you could. And, if you have a stack of three <div>s, with <h3>s inside each level, if you do

div div h3 {

}

you’ll get both of the bottom two <h3>s. So the selector operation in CSS is not exact-match-only. Since our <h3> in the bottom of the stack has three <div>s around it, it will trigger on any CSS applied to div h3, div div h3, or div div div h3.

<div>

<h3>Level one</h3>

<div>

<h3>Level two</h3>

<div>

<h3>Level three</h3>

</div>

</div>

</div>

2. To select with more specificity use the > operator. So if I want to select only <p>s that are *directly* children of <div>s (i.e., no interceding elements), then I type

div > p {

}

instead of

div p {

}

The latter will also include a <p> that is a child of an <ul> that is in turn within a <div>, for example. Specific rules override general rules.

3. Asked my first StackOverflow question – answered within minutes! It’s a pretty amazing site, like having a bunch of people more knowledgable than you help you for free, providing you put in the work to ask good questions and search for pre-existing answers:

4. Classes vs. ID’s – Classes (the “fancy” class would be referenced as .fancy {} in the stylesheet, e.g.) are used for multiple HTML elements that need the same styling. ID’s are used for just one element (they ‘ID’ a specific element, get it?). #fierce {} in your stylesheet would reference the “fierce” id in your HTML.

5. Pseudo-class selectors – recall the HTML tree – <html> is the root, then <head> and <body> form two branches, with all the <body> children form branches/sub-branches of <body>. It’s easy to locate an element within the HTML hierarchy this way, but *state* about the element is not represented in our tree. Pseudo-class selectors let us do this. For example,

a:link{

}

a:hover{

}

a:visited{

}

in your stylesheet will define how an unvisited link, a link the user’s mouse is hovering over, and a visited link are styled.

To set the class or id of an html element you do <p id = “fierce”> or <p class = “fancy”>.

6. Playing with display – display as a property is pretty interesting. display:inline-block can be used to create navbars, as the CodeAcademy tutorial says. That’s a pretty nifty use that I didn’t think of, for what I kind of felt was a boring tool. I think it really requires some out of the box thinking to see how you can apply simple rules to create complex or useful patterns. Maybe using more CSS will let me get a quicker grasp of how a tool can be useful in the future.

7. Hidden HTML elements – interesting, negative margin values can let you hide an HTML element completely from a page. I can see how SEO spammers might try hiding keywords in a div positioned off the page to drive traffic to their page. I’m sure there are even more uses for them. I wonder if there are legitimate uses for them? It seems like it would have to be something you don’t want the user to see, but you need to be an HTML element instead of a javascript variable for whatever reason.

8. Positioning – this seems tricky. Static, Absolute, Relative, they seem to do different things but I’m not sure how. Fixed seems really cool since it glues the element to the screen, so that when the user scrolls the element’s positioning stays the same.

 

6/20/2014 (Fri)

Yay! Today I get to start javascript! Excellent. My hope is that learning javascript provides me with the ‘logic engine’ necessary to actually power the app I want to develop. Storing state, modifying the display, handling user actions, communicating with the server, etc. Exciting exciting!

What I did:

1. Read Introduction and Chapters 1 and 2 of Wrox’s Professional JavaScript for Web Developers

2. Finished the “Introduction to Javascript” section of Code Academy’s JavaScript course.

3. Experimented with JSFiddle and Google Dev Tools’ console, decided I liked JSFiddle better, though Dev Tools will probably be quicker for when I’m working in the future.

4. Reading through Chapter 3 of Professional, while it was interesting at first it got old quickly. Data types are probably the most boring thing in the world. I’m reading words and not really understanding what they mean by the time I got to Objects. No idea what’s up with them, other than you need the new command to make them.

Finally made it through to Statements (p. 69), where I will stop today and pick up with next time!

Cool things I learned:

1. Professional claims that today script references for external .js files are usually put at the end of the <body> tag so that the browser starts rendering the <body> faster, reducing the amount of time spent on a blank webpage. Previously they were put in the <head> tags, which required they be downloaded and processed before rendering began. Cool UI hack. But I wonder — if JS is essential to the rendering of the page content, shouldn’t it be loaded first? I guess in some cases a significant amount of layout can be managed with the default CSS and html without worrying about js having been applied yet. But maybe if a user is coming from a previous page this is not the case, since some state about their actions may change what should be rendered here. Perhaps this is what AJAX is.

2. <noscript> allows you to display a message to users whose browsers have javascript turned off. Only they will see it, regular users won’t! Pretty great, always wondered how they did that…

3. It seems like DOMContentLoaded is the last event to fire for the DOM being finished, but, in some cases (defer or async on your js code) javascript may continue to execute after this event.

4. JavaScript has two different equality comparisons, === and !== vs. == and !=. Use === and !== always.

5. Professional‘s section on Semicolons is blissfully short and to the point. The answer – use them. The benefits – makes sure you finish what you were doing, aids in code compression (since whitespace can be removed), and prevents parsers from placing semicolons where they don’t belong. The same (pretty much) goes for code blocks – always use braces.

6. All variable declarations have local scope, and will be destroyed once control passes out of the local scope.

7. Use null as an empty object pointer. If you have some variable that later will be given a value, initialize it to null, so that later you can say if (myVariable != null) { do something }. But, don’t initialize to undefined.

8. The conditional operator is pretty sweet. It conditionally assigns a value to a variable based on the evaluation of a boolean test. For example.

var max = (num2  > num3) ? num2 : num3;

If num2 > num3, max = num2. Else max = num3. Pretty cool, it’s like an abbreviated if statement collapsed into a variable declaration and initialization.

 

6/23/2014 (Mon)

Today we make more strides in javascript. Gonna finish up chapters 3 and 4 of Professional and get cracking on the Codecademy stuff!

Focus for today: I want to be better about actually typing in all the examples I come across in the book, even if they seem trivial. I think I’ll get more retention this way.

What I did:

1. Finished Chapter 3 and started Chapter 4 of Professional.

2. Came across a question concerning the dynamic linkage between the arguments[] object vs. named arguments in functions, on page 82 of Professional. As I wrote up my question to ask on StackOverflow, it suggested a similar question to look at first, and yes it did have the answer!

If “use strict”; is enabled, then there is no dynamic linkage between arguments[] and the named arguments because strict mode is enabled. Otherwise, there is a dynamic linkage and changing one (e.g. arguments[1]) changes the other (e.g. num2, for a function doAdd(num1, num2)), in both directions.

3. Learned about the difference between the stack and the heap, and how they relate to the OS

4. Asked a good question on StackOverflow concerning dynamic properties of primitive variables (impossible in js) and reference variables (possible in js). As a result learned about bitwise AND (&), the comma operator (,) and the simple assignment operator (=).

5. Looked over an old CSS question I had asked on StackOverflow. This was a good way to get my brain to ‘recognize’ CSS again and helped increase retention (“Oh yeah, ID’s are referenced as #id in the .css file, and classes as .class…”). Also reminded me that I really should rewrite that question from scratch =\

Cool things I learned:

1. More about local scope – it’s not quite as local as I thought. There are no block-level variables, so a variable initialized and defined inside a for loop is still accessible after the loop finishes executing. So scope must be local only to functions, not to code blocks.

2. “for in” is a cool loop. It looks like this:

for (var propName in window) { document.write(propName); }

It iterates through all the properties in a given variable. You should test the variable to see if it is null or undefined before you call for in, since some older browsers will throw an error instead of skipping the code block if the variable is null or undefined.

if (window !== null && !== undefined) { for (var propName in window) { document.write(propName); } }

3. The “continue;” control is really cool. Unlike “break;” which just escapes the loop, stopping it permanently, “continue;” skips this iteration of the loop but keeps the loop going. This is one way you could implement a control condition like “skip all instances where the variable is divisible by three.”

4. You can use “continue” and “break” with labeled loops (labelName: for (blah blah blah)), to direct the control flow more explicitly. You can tell the program which loop to break (e.g. the outermost loop) or which loop to continue at. Using “continue” or “break” without an argument just continues at / breaks the most immediate loop. Useful for nested loops, but evidently overuse can break things sometimes.

5. Switch statements can evaluate expressions as conditions in javascript. So the following is valid.

var num = 23;

switch(true) {

case num < 23:

alert(“less than 23”);

break;

case num > 23:

alert(“greater than 23”);

break;

default:

alert(“is 23”);

}

The evaluation condition uses the identically equal operator (===) so no type coercion happens. You can also evaluate on strings or functions, not just numbers.

6. Any function can return any value of any type at any time. All you have to do is write “return variableName;”. return breaks execution of the function. You can use it like this: var result = sum(5, 6); where sum(a, b) { return a + b; } has been defined as a function. Invoking return without an argument just breaks function execution, and returns “undefined”. Functions should either always return something or never return something.

7. This is huge – functions just don’t care about data type or number of arguments. Quoting Professional p. 81 – “Unlike in other languages, naming your arguments in ECMAScript does not create a function signature that must be matched later on; there is no validation against named arguments.” As a consequence, all function names must be distinct or you will overwrite previously defined functions with the most recently defined function.

8. You can use arguments[0] to access the first argument passed to a function, and arguments.length will give how many arguments were passed to the function (like an array). You can pass more or less than the number of specified arguments to a function, and it will still run. Argument names are there just for the human reader. Changing the arguments[x] value within a function will change the corresponding named value, and vice versa.

9. Reference variables are on the heap and can be objects that have properties. Primitive variables are on the stack and cannot have properties. Reference variables are actually pointers to locations in memory. Copying them copies a pointer. Primitive variables are the actual location in memory (on the stack) where the value is: they are the ‘raw’ value. Copying them creates a new location on the stack with the same raw data. Changing a reference variable (an object that can have properties) will change all variables that have been assigned the same reference, because it is what the pointer points to that is changed. Changing a distinct copy of a primitive variable will not change the other copies, since they access different locations in memory with different raw data.

10. Variables are always passed by value (not by reference) in arguments to functions. This means with arguments that are primitives, the original primitive passed to the function will not be changed. With arguments that are references, the pointer will be copied into a new, local variable that is the function’s argument. Changes to that local variable will of course be accessible by the original variable after the function ends, because the heap is globally available and both pointers point to the same object. However, creating a new object inside the function and assigning it to the argument’s variable will not change the heap location that the original, external object’s pointer references. This is because creating a new object inside the function creates a local variable pointing to a different location in memory. This is because the variable was passed by value rather than by reference. — To be honest I’m a bit shaky here, but it seems to work intuitively, so I’ll leave it be.

 

6/24/2014 (Tues)

I need to start formulating these notes into blog posts, probably one post per week, with the notes for each day enclosed. I should also probably roundup all the StackOverflow links I look at with short descriptions of what I got from them. Today we continue Chapter 4 of Professional, hopefully finishing it and getting to Codecademy stuff for javascript (btw, anyone else not realize it’s “Codecademy” not “Code Academy?”).

I also want to look back at HTML/CSS stuff just to jog my memory again.

Finally, back to real coding in Codecademy today!

What I did:

1. Reviewed my notes from the previous day, looking over the Stack Overflow questions I encountered, and adding some more detail concerning function signatures (they don’t exist, so make sure all your functions have different names).

2. Finished reading Chapter 4 – It’s useful to have the link for a technical book’s errata page handy. It can save you lots of time scratching your head at why something in the book doesn’t make sense! (E.g. p. 92 on function contexts)

3. Did Section 2 (“Functions”), Section 3 (“For loops”) and most of Section 4 (“While loops”) of Codecademy javascript.

Cool things I learned:

1. I noticed you don’t need var to declare a variable, and learned when you use it (always, unless you explicitly want a global variable) and why. Quoting the Mozilla Developer Network reference – “Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.”

2. typeof and instanceof – allow you to determine a primitive type or a reference type. typeof x returns what type x is: number, boolean, undefined, string, or object. x instanceof Object returns true/false if x is/isn’t an Object (if it’s a reference variable it will always return true here). You can use this to test if x is an array by typing x instanceof Array

3. Execution contexts (scopes) form a “scope chain” along which identifiers are searched for. These nest, from outside to in, and are searched from inside (most specific) to out (the outermost is global). In javascript it’s usually executing in a browser, so the outermost context is the window object’s variable object. The global variable object does not have an “arguments” object.

4. This seems tricky – there is no block-level scope. A variable defined inside a code block like an if statement or a for loop is still accessible, globally, afterwards – provided that the code block is in the global execution context (i.e. not inside a function). “When a variable is declared using var, it is automatically added to the most immediate context available” (94).

5. Be careful using the same variable name twice – a local variable in the current execution context takes precedence over a global one, since it is at the front of the scope chain. So if a local variable and a global variable have the same name, the local variable is the one that will be accessed.

6. Global variables, or properties of global objects, should be dereferenced once you’re done with them. Dereference them by setting them = null. E.g.,

var globalPerson = “Bob”;

// do stuff with Bob;

globalPerson = null;

This signals to the garbage collector that the variable can be marked and swept and its memory reclaimed. I can see that programming like this really requires you to be on top of your game and know when you need a variable and when you don’t. You have to be really aware of execution flow and also of the logic of the application you have designed.

7. There is a subtle but meaningful difference between two ways of declaring functions.

It turns out one is a function declaration, which results in a named function. The other is a function expression, which results in a variable being assigned an anonymous function.

Function Declaration:

function colorSwap(){

//code

}

 

Function Expression:

var colorGrab = function(){

//code

};

*Note the semicolon in the function expression.

When you call .toString() on these, you get different outputs. colorSwap.toString() will give you the function’s name and then the code block. colorGrab.toString() will give you an anonymous “function()” followed by the code block.

Having a name associated with a function (using Function Declaration) can be helpful when debugging, since you can know which function is running. Also, named functions can be called before their definitions – they are available once they are defined somewhere (not sure how this interacts with scope, I’m guessing a function declared inside another function is not globally available). Function Expressions must occur before that variable is called.

This answer has a good explanation of “function hoisting,” which is the requirement that all declared functions get loaded before any code is executed (which is why they’re accessible from the beginning, unlike function expressions).

 

bobo

 

One thought on “Zero to One: Building Mamoru – Weeks 1 and 2

Leave a Reply

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