Javascript Event Loop – Javascript Fundamentals

Again, welcome to Javascript Fundamentals (gameshow voice), where I recap my notes about… well, Javascript Fundamentals =)

This isn’t meant to be a lesson on the Javascript Event Loop – merely my regurgitation of thoughts and notes – so don’t expect eloquent paragraphs of enlightenment…


This video gives a great breakdown of the Javascript Event Loop.


Oh, and also see this article by Mozilla on the Javascript Event Loop

Screen Shot 2016-02-20 at 9.37.19 AM

  • JavaScript has a concurrency model based on an “event loop”
  • Stack: Function calls form a stack of frames (records the state of where we are in the program)
    • When a function is called/invoked/executed, a new local execution context (scope) is created containing it’s arguments and local variables.
      • The new local execution context also contains also contains a reference to the outer scope (scope chain)
      • The new local execution context also contains a ‘this‘ object is created (pointing to the object that invoked the function)
    • When another function is called/invoked/executed, a second local execution context (scope) is created and pushed on top of the first execution context.
      • The new local execution context also contains it’s own arguments and local variables, etc etc.
    • When the second function returns, the top execution context is popped off the stack.
    • When the first function returns, the stack is empty.
  • Heap: Objects are allocated in a heap (a large mostly unstructured region of memory).
  • Queue: A list of messages (each associated a function) to be processed that is in each Javascript runtime.
    • When the stack is empty, a message is taken out of the queue and processed (calling the associated function).
    • Calling the associated function creates an initial stack.
    • The message processing ends when the stack becomes empty again.
  • Event Loop:
    • Has one job – look at the stack and task queue.
    • If the stack is empty, it takes the first task on the queue and pushes it onto the stack.
    • DOM events (click, etc) or callbacks are pushed to queue


Interesting Points (from the video):

  • setTimeout is not a guaranteed time to execution, it’s the ‘minimum’ time to execution.
  • Long-running (blocking) Javascript code can affect browser rendering.
    • Rendering is blocked when the call stack is not-empty, aka. “Don’t block the event loop”. See 20:14 marker in video.

Closures and Scope Chaining – Javascript Fundamentals

Welcome to Javascript Fundamentals (gameshow voice), where I recap my notes about… well, Javascript Fundamentals =)

I’d gone through an amazing Javascript video lesson prior to the bootcamp called Javascript: Understanding the Weird Parts, by Anthony Alicea. Back then it was actually way too in depth, and I knew that I needed to revisit the content again to really understand and appreciate the concepts that he was teaching: Scope, closures, prototypes, ‘this’…


So that brings us to today’s recap: Revisiting Javascript Closures and Scope Chains! Yay!

(Oh, I also came across this video “Javascript Scope Chains and Closures” which is really good – check it out as well. It starts off a bit slow, but the speaker, Adam Breindel, is really clear and concise)


Oh. And this isn’t meant to be a lesson on Closures and Scope Chains. They’re just a regurgitation of my thoughts and notes – so don’t expect eloquent paragraphs of enlightenment…

Javascript Engine Pointers

  • When a function is invoked/executed, the Javascript engine creates a new local scope for that function.
    • Every function INVOCATION, has a separate scope
    • Local variables are declared with var and are scoped to the function they are declared within
    • There’s a correlation of the lexical environment (where something is), and the scope
  • When a function is invoked/executed, the Javascript engine looks in the local scope for any referenced properties
    • If no property is found in the local scope, it will work its way outside through the scope chain, looking for that property name. It keeps going until the scope chain reaches global scope


Closure in summary: A nested function (function in a function) will keep a reference to the enclosing (outside) function’s scope environment (aka. the variables, and properties defined in that scope during invocation), through the scope chain.

  • Closure: a permanent link between a function and its scope chain
  • Anytime a function is invoked, it runs with a scope chain based on where it was defined
  • The nested function will have access to the variables outside, through it’s reference to the outer environment (scope chain)
  • When a nested function is invoked outside of its original scope chain, the original scope chain resolution will still work
    • Basically: the nested function still keeps a reference to the outer (chain) scopes, and all related scope properties


Where Closures Generally Come Into Play:

Any type of async callback utilizes the concept of closures – to allow the callback function invocation to utilize variables and scopes that were defined in while the containing scope was run

Explicit Closure Use

  • Javascript encapsulation is only really available through function scopes
  • Create a function and use its private/local scope as the mechanism of encapsulation (the scope contains private locals)
  • To define and expose the interface, we return an object with access to the internal locals (through scope rules)
  • See Module Pattern
    • Separates the interface from implementation

OC|CS Bootcamp Cohort 3 – Graduated!

That’s right! I graduated from Orange County Code School‘s Cohort 3!

I’m now officially unemployed! So, a couple of house keeping things:

Hire me!



For those who are just joining us

(or… whoever even reads this blog because I don’t actually track my analytics. I know, you’re probably saying:
“And you used to do SEO? Don’t you guys live on Page Views or some other vanity metric?”.
Nope, I blog for the fun of it! //I digress)


As I was saying. For those who are just joining us, Orange County Code School (OC|CS) is a Full-Stack JavaScript Immersive Bootcamp, where students engage in over 540 hours of intensive coding in Full-Stack Javascript, over 3-months.

During these past 3 months I learned full-stack web development primarily focusing on the MEAN stack (MongoDB, Express, Angular.js, Node.js).
I say primarily focusing on, because I got over-eager and also researched and implemented, React.js, and D3.js into my second project (It ain’t a bootcamp until you’re feeling the burn, right?).

Was it worth it? For me, it was worth it. The 6-hours-a-day in-class work environment was exactly what I needed to zone in and pick up the skills to be able to build apps using modern web technologies.


Here’s a summary and key achievements of what I built during the course:

Project 1: TravelGram – An Instagram geolocation photo discovery web app

Travelgram is a photo discovery app that allows users to search for a location in the world and view geolocated Instagram photos that were taken at the searched location.

The Google Places API is used to retrieve the latitude/longitude of the searched location and a request is made to Instagram to retrieve geolocated photos within that latitude/longitude.

The returned Instagram photo data is used to dynamically render DOM elements into a gallery. At the same time, markers are plotted into Google Maps according to the specific latitude/longitude of where each individual photo was taken.

Hovering over each photo will highlight the corresponding marker to show you where the photo was taken (and vice versa), which is achieved by tracking each Goole Maps marker and corresponding photo with an array.

Github –
Live Demo –
(Search Paris, London, or Shanghai for demo. Limited results due to Instagram Developer Sandbox)

Key Acheivements:

  • Learned and implemented API calls, Sass, CSS flexbox, and map-marker highlighting, through self-study
  • Dynamic DOM generation with Javascript to populate Instagram gallery and map markers depending on user search
  • Javascript event-listeners highlight map-markers on hovering over a Photo (and vice versa)
  • Responsive design and positioning with CSS3 flexbox and media-queries
  • Dynamic grid layout as screen size decreases, with Bootstrap 3 column classes
  • Generated DOM elements from returned JSON data, from AJAX calls to Instagram API and Google Maps API

Skills: Javascript, Traversing Arrays, AJAX, Instagram API, Google Maps API, Google Places API, Git, Github, HTML5 (Jade), CSS 3 (Sass), Bootstrap 3, Responsive Design, Balsamiq 3


Project 2: Twitterment – A Real-Time Twitter Sentiment Dashboard

Twitterment (Twitter Sentiment) Is a real-time Twitter sentiment dashboard that analyzes and graphs the sentiment of a tracked keyword.

Twitterment listens to the Twitter Streaming API for the searched keyword. Received Tweets are analyzed with an AFINN-based sentiment analysis npm module, and the analyzed Tweet object is sent to the client.

Node.js (Express) and is used on the backend to achieve real-time client-server updates when new tweets are received on the server. React.js is used as the view layer to manage DOM rendering of new Tweets in real-time with a reusable React TweetCard.jsx component. D3.js is used to render each sentiment analyzed Tweet onto a line graph to show the sentiment trend since the search started.

Regarding D3 and React integration, Twitterment uses React to handle DOM manipulations for plotting Data Points (DataPoints.jsx) and Line Paths (LinePath.jsx) for the line graph. This decision was made since React already knows when to rerender the graph when new tweets are received and the tweet counts are updated in the app.

Github –
Live Demo –
(Note, there is a Twitter API limit on the live demo. If it doesn’t work, please try again the next day!)

Key Achievements:

  • Learned and implemented React.js,, and D3.js through self-study (was not taught in class curriculum)
  • Websocket server on Node.js, Express, and to enable real-time ‘push-data’ functionality from server to client
  • React.js front-end with modularized and reusable React.js components for maintainability
  • Utilized React.js component lifecycle to animate sentiment analysis hit-counters
  • D3.js real-time multi-line graph visualize sentiment Tweet data over time
  • Use user-entered keywords to monitor the Twitter Stream API in real-time

Skills: Javascript, React.js, D3.js, Node.js, Express,, Twitter API, Git, Github, HTML5, CSS 3, Sass, Bootstrap 3, Webpack, npm, Balsamiq 3


Project 3: Twitterment – A Real-Time Twitter Sentiment Dashboard

ToDoIt is a full-stack MEAN (MongoDB, Express.js, Angular.js, Node.js) app that allows users to sign up for an account and store To Do items to their account.

TodoIt was built with a RESTful ‘API first’ process on Node.js, Express, and MongoDB. This approach provided helpful constraints to focus development on creating functional CRUD processes that could be tested using Postman. With functioning REST API endpoints, development could be focused on the frontend.

A normalized data structure with two separate MongoDB collections are used to store User accounts (with password hashing) and Todo items. Each To Do document stores a reference to the User ID that the To Do item belongs to. A MongoDB search on the Todo collection, by user ID, ensures that each user only sees To Dos they own.

Passport.js is used to authenticate users and create a session which is stored as a cookie, and Passport attaches req.userwhen a user is logged into a session. req.user is attached to the window object as window.user to allow Angular.js to conditionally show/hide elements, like a Logout link, if the user is logged in.

API endpoints that require user authentication are also protected using a custom middleware that uses Passport’s req.isAuthenticated() to either return next(), or returns a status code of 401.

On the frontend, a custom Angular.js factory service allows the Todo controller to make AJAX CRUD requests to the aformentioned API endpoints. TodoIt uses Angular’s $routeProvider to serve partial html views according to defined URL routes, and ngRepeat is used to render To Do items. ngShow provides a simple method of conditionally showing/hiding UI elements depending on whether there are To Dos and completed To Do items.

Github –
Live Demo –

Key Achievements:

  • RESTful server API endpoints built on Node.js, Express
  • MongoDB stored todos and user-accounts with hashed passwords for security
  • Username/Password login authentication and cookie session management with Passport.js
  • Modularized AngularJS modules and controllers to separate functionality and improve code maintainability
  • Reusable AngularJS service with $resource to CRUD todo items with backend API

Skills: Javascript, Angular.js, Node.js, Express, MongoDB, Mongoose, Passport.js, Bcrypt, Git, Github, HTML5, EJS, CSS 3, Sass, Bootstrap 3, Bower, Gulp, npm, Balsamiq 3

Angular Performance Tips

We had our final OC|CS Demo Night last night at the Sony Gaikai Offices (really really cool place!), and I had the awesome opportunity to talk to a bunch of recruiters and developers.

One of the things I really appreciated from last night’s Demo Night was that several developers who attended asked to look at my code. Rob, who is a Sr. Product Engineer at Mossio, gave me some great feedback on my code structure and tips on using Node environment variables to protect sensitive keys for privacy.

I also got to chat with Isaac, who is a Developer at Sony Gaikai. He pointed me to look up some resources about Angular performance precautions with using $scope.$watch and also suggested I look up Bind Once :: to also improve performance.

Isaac explained to me that I should be careful in using $scope.$watch because I can potentially run into performance issues on larger Angular applications.


The eager developer that I am =p, I did more reading and I found this primer on Angular performance: 11 Tips To Improve AngularJS Performance.

Essentially, Angular performance issues usually arise when there are too many watchers in the app (or inefficient uses of watchers), since Angular uses dirty checking on the digest cycle to keep track of all the changes in app. (Aka, Angular goes through every watcher to check if they need to be updated).

Likewise, using Bind Once :: can be helpful for values that aren’t going to be updated. The example that Isaac gave was the name/username of a person’s account. By using Bind Once, Angular binds the value once, but then doesn’t check to see if the value is updated in the future – thereby reducing the amount of watchers in the digest loop.


This is my third? week using Angular so it’s great to be able to get some tips from more experienced developers. Thank you to everyone who has supported me through this bootcamp!

It Ain’t Over Until the Fat Arrow => Sings…

I know what you’re thinking: “What a terribly chosen blog title for SEO…”. At least, that’s what I thought when I first wrote it… //I digress


Anyways. I was soooo confused on understanding arrow functions. I didn’t even know they were defining functions! I wish Google did a better job at returning relevant results when searching for “javascript =>”.

I just wanted to reference this handy post by StrongLoop: “An Introduction to JavaScript ES6 Arrow Functions” (Now that’s a great SEO title…)

Arrow functions serve two main purposes:

  • more concise syntax
  • sharing lexical this with the parent scope


Here’s an example of how a function can be written using arrow notation:

function () { return 1; }
() => 1

I also appreciated the summary from that article:

It might be very tempting to just start using => instead of function everywhere. I’ve seen whole libraries written just using => and I don’t think it’s the right thing to do because of the special features that => introduces. I recommend using arrow functions only in places where you explicitly want to use the new features:

  • Single statement functions that immediately return (lambdas)
  • Functions that need to work with parent scope this


Intrigued? Read: “An Introduction to JavaScript ES6 Arrow Functions”


MongoDB: What is Normalized Data?

Alright! We’re on week 9 (out of 12) of our Orange County Code School bootcamp – four more weeks left! I’ve just wrapped up my 2nd project and will be doing a recap post about it soon. We’ve been learning about MongoDB and MongooseJS in class. Mongoose is an object modeling package for Node, and allows access to the MongoDB commands for CRUD (Create, Read, Update, Destroy).

I was doing some exercises, and came across two terms that I had no idea about: Normalized Data, and Embedded Data. Yeah, I know… what?

Here’s a quick recap from me reading of


Normalized data models describe relationships using references between documents.

Basically, there are no embedded documents (the stuff between the curly {}), within another document. In the graphic below, you can see that the _id of the user connects all three documents (user, contact, access) together.


In general, normalized data models should be used when:

  • embedding results in duplication of data, but would not provide sufficient read performance advantages to outweigh the implications of the duplication.
  • to represent more complex many-to-many relationships.
  • to model large hierarchical data sets.


Embedded data models allow applications to store related pieces of information in the same database record. As a result, applications may need to issue fewer queries and updates to complete common operations.

Basically, there are embedded documents (the stuff between the curly {}), within another document. In the graphic below, you can see that there are additional documents (contact, access) included into the main document.


In general, embedded data models should be used when:


Async Javascript with Promises

I’ve been struggling with understanding promises for a while but I found this video by Kyle Young really clear and helpful! I definitely recommend it to anyone also trying to better grasp the idea.


After watching the video, it made this article a lot easier to digest:

This code from the above article sets up a nice Promise Pattern on the XMLHttpRequest

function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {

    // Set up an XHR Object
    var req = new XMLHttpRequest();'GET', url);
    req.onload = function() {

      // This is called even on 404 etc
      if (req.status == 200) {
        // Resolve the promise with the response text
      else {
        // Otherwise reject with the status text

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));

    // Make the request


This allows the XHR to be used in a really neat promise pattern:

  .then(function(response) {
    console.log("Success!", response);
  .catch(function(error) {
    console.log("Failed!", error);

Real Time with React.js and

Update: Found these great articles on React.js. Wish I read them before I started my project! It would have made me feel a lot less depressed that I was taking such a long time to pick up the concepts of React!

ReactJS for Stupid People
Flux for Stupid People


As I briefly mentioned in my previous post, I was slightly too gung ho in choosing my second project: Twitterment. The idea behind Twitterment is that it’s an app that allows brands to view the Twitter sentiment around their brand keyword on a dashboard.

Problem 1: I was really attracted to the concept of having a real-time updating app, so that drew my attention to Twitter’s streaming API. I found out quite painfully though, that real-time I/O is not so simple to work with (at least, we didn’t learn about how to deal with real-time). Problems started to arise when I tried to make server-side AJAX requests to Twitter’s stream. I soon found out that once I send a server response from my Node server back to the client, I can’t keep pushing new Twitter stream data to the client.

Problem 2: I also tried to gather Twitter stream data into an array and send chunks to the client, but then I came across another performance issue where I was constantly repainting the DOM when I wanted to update the refreshed list of Twitter data. Yup, trouble.

So with a bit more research I realized that a possible solution to work with real-time stream data was to use, and React.js could help solve some performance issues with frequent DOM updates.

It took me a painful 2 weeks to learn the basics of React.js and, and refactor my app to implement both of these technologies. I say painful because I felt like I was making no ground for two weeks, while my classmates were hacking away – I had a couple of moments where I wanted to just trash the whole project and do something more straightforward!


Anyways. Drama aside – React.js and is actually really interesting to work with, now that I’ve gotten a better idea of how these technologies work. essentially works by adding event listeners to an instance of my Express (Node) server, and adding a global socket variable that acts as an EventEmitter-like object on the client. So what I can do is attach a listener to trigger when certain events are emitted from my server (aka. run a function to update my list of Tweets on the client when the server receives new data from the Twitter stream!)

Even more cool is that both the server and client’s Socket object act as EventEmitters, so I can emit and listen for events in a bi-directionally (aka. If I can send a search keyword to the server, to track on Twitter’s stream). Beautiful! That takes care of sending and real-time data between my server and the client. Problem 1 solved. whew! =)

React.js is another library that provides a way to create interactive, stateful & reusable UI components. React uses a “Virtual DOM” that selectively renders nodes based upon state changes, while doing the minimal amount of DOM manipulation to keep my components up to date. Essentially, React uses a “diffing” algorithm to identify what has changed, and then goes through a process of “reconciliation” to update the actual DOM with the results of diff (aka. When I have new Tweet added to my array of Tweets, only the new Tweet will be rendered onto the DOM, instead of the whole list! Sounds exactly like what I need to solve Problem 2!).


Well, that’s the story so far. As you can see in the screenshot below, I’m still in the process of coding out this app, but the Twitter Stream is real-time and fully functional using React.js and! Stay tuned or follow along on my GitHub repo:


Project 1 Recap: TravelGram

Okay, this post is over due, but it’s been really busy!

So my first project, dubbed ‘TravelGram’, has been a really fun experience (unlike my current second project, which is giving me sooo much grief, but that’s another story for another day… heh).

You can check out the GitHub repository here:


The idea behind TravelGram is that it’s a web app for travelers who want to explore a location before they go there. TravelGram allows users to search for a location around the world – Shanghai, for example, and the website will pull in geolocated pictures from Instagram.

The technologies that I incorporated to build out this project were:

  • Instagram API
  • Google Maps API and Places Library
  • AJAX
  • SASS and Jade
  • Bootstrap 3
  • A lot of beautiful CSS and Javascript animations (if I may say so myself =p)


Some of the cool features that I build out were:

  • Dropping marker pins where each individual picture was taken
    • This was done by creating an array and assigning each photo and marker an ID
    • An event listener for mouseover and mouseout is attached to both the marker and photo
  • Hovering over the picture highlights the respective map pin
  • Hovering over a marker on the map highlights the respective picture

Note: The filtering panel above the photos doesn’t work yet – I didn’t have time to finish that functionality, but the idea is there =)


The big success of this project is that it was only actually supposed to be a demonstration of the HTML/CSS front-end development skills that we had just finished learning in class. So the fact that I was able to pull in extra functionality with Instagram and Google APIs was really cool. I’m really pleased with everything that I was able to build out. Were were also only just starting to learn Javascript during the first week of the project, and so a lot of the functionality was built out through weekend research and side reading.

One of the main layout techniques that I was practicing in this project was CSS FlexBox. I found it to be a really powerful way to align and position components without the headache of thinking about floats and clearfixes. It requires a lot of prefixing to allow for cross-browser compatibility, but using an auto-prefixer helped with that =)



Some of my take-aways from this project:

  • Bootstrap is great for building out layouts quickly
  • Bootstrap can end up being really difficult to work with in fine-tuning layouts because of the way that rows and columns work. This article really helped to clear up some confusion: The Subtle Magic Behind Why The Bootstrap 3 Grid Works
  • Google APIs are pretty great to work with. Their autocomplete library implementation was literally just a couple lines of code to use
  • Instagram’s API is not so fun to work with. I was placed in a sandboxed as a new Instagram developer and had to send off a lot of request emails to friends to use their geolocated Instagram photos =)


I was also one of the 6 students selected (out of our class of 19) to present my project at the school’s Demo Day to some recruiters and CTOs in the Orange County area. Here’s a quick mug-shot that my wife got of me giving an intro to what we’ve been learning in class =)



Random Weekend Javascript Musings: “for… in”

edit: Well what do you know; I was doing some light reading of Underscore.js’ documentation (yes, the things that I do in my free time…). But! I found out that Underscore.js has an Object Function to retrieve the names of it’s keys. Link.

_.keys({one: 1, two: 2, three: 3});
=> ["one", "two", "three"]



We’re getting into NodeJS concepts and exercises in class, and with that, we’ve been looking at JSON as a data format. ‘For loops’ are pretty standard examples in class to loop over the values in a Javascript object, and that’s when I had the random thought: “what if I want to get the name of the key? How do I do that?“.

Of course, that led to some research and I came across the for…. in loop. I’m pretty sure I’d learned it before in my codecademy or pre-OCCS prep work, but since it hasn’t been used so far in class, I decided to really dig into it. I really enjoyed this read: Exploring Javascript For-In Loops

Anyways, so here’s a method of getting access to the name of keys in an object:

for (var variable in objectExpression) {statement}

var myObj = {a: 1, b: 2, c: 3};
for (var property in myObj) {
console.log(property + ': ' + myObj[property]);
//a: 1
//b: 2
//c: 3


Be warned. Using for… in loops can cause prototype extensions of your objects to show up. I don’t wholly understand this concept since we haven’t learned about prototypes yet, but here’s a note nevertheless. Yes, more research lined up for me this afternoon =p

var arr = ['a','b','c'], indexes = [];
Array.prototype.each = function() {/*blah*/};
for (var index in arr) {
indexes; //["0", "1", "2", "each"] whoops!

Read more on Exploring Javascript For-In Loops