JS Questions: What’s the Event Loop?

This is the eleventh in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

What’s the Event Loop?

Like any programming language, JavaScript has a specific process for handling function calls in a program, and more specifically, deciding when each function will run. Unlike other languages, JavaScript can be run in a browser, meaning that users may be interacting with the program by clicking a mouse or scrolling, for instance, simultaneous to other processes that are already running. The event loop helps create a fluid experience for users, by dictating a flow that allows for relatively long running processes to occur alongside client-side interactions.

Without features built into Node and browsers, JavaScript would only be able to handle one event at a time. Each function call would be added to a stack and one-by-one, popped off the top and run. It’s easy to imagine how this could become problematic in a web app. If a notice telling a user she had successfully updated her account were rendered to a webpage for three seconds using setTimeout, the user would not be able to interact with the page until the setTimeout had completed.

Some events do happen synchronously in JS. Loops will run in the call stack and prevent a webpage from re-rendering until they have completed.

However, due to the event loop built into browsers, processes such as AJAX requests and timeouts can run in the background, with their callback functions placed in a queue that are added to the call stack only when the entire stack has cleared. The below code snippet illustrates this.

If you paste this in your console, you’ll see 1 logged, then 2 returned, then 3 logged. Here’s what happens:

  1. The eventLoop function gets added to the call stack.
  2. The setTimeout timer begins and the callback function is added to the queue after 0 milliseconds.
  3. The number 1 is immediately logged.
  4. The eventLoop function returns 2 and the call stack is cleared.
  5. The setTimeout callback runs, logging 3.

Note that the call stack runs functions in ‘first in last out’ order (meaning that the first function added to a stack is the last to run). That’s why, in the code below, the strings are already concatenated when logged:

First, the greet function is added to the call stack. Then, the concat function is added to the call stack. Concat runs, the greeting is logged, and the greet function is cleared from the stack.

Meanwhile, the queue runs callback functions in ‘first in first out’ order. The first item added to the queue is the first to be added to the call stack. That means, if multiple AJAX requests are made, for instance, the first request to finish will be the first to have its callback function run.

In sum, the event loop in JavaScript refers to the synchronous and asynchronous flow dictated by the call stack and queue in browsers.

Resources

 

Advertisements

Useful Terms while Tackling Learn.co

The difference between the Flatiron School’s free learn.co lessons and other free online resources to learn coding is that learn.co requires you to use the tools and software that a professional would. Getting comfortable in the environment is certainly a worthwhile endeavor, but I definitely found it confusing and intimidating at first. Here are some terms I’ve run into and become familiar with recently:

Console/Terminal: From Wikipedia, “A computer terminal is an electronic or electromechanical hardware device that is used for entering data into, and displaying data from, a computer or a computing system.”

 Shell: From Wikipedia, “In computing, a shell is a user interface for access to an operating system’s services. ” 

IRB: stands for Interactive Ruby, a REPL where code is typed in a command line and immediately executed.

REPL: stands for Read-Evaluate-Print Loop. Takes input, evaluates, and prints immediately.

Pry: A REPL alternative to IRB that can be used for debugging.

Mocha: From the Mocha website, “feature-rich JavaScript test framework running on Node.js and in the browser.”

Debugger: From W3Schools, “The debugger statement stops the execution of JavaScript, and calls (if available) the debugging function. Using the debugger statement has the same function as setting a breakpoint in the code.”

My Strategies for Learning to Code

When I first started learning to code, I didn’t have much of a strategy. I floated between podcasts, Codecademy, and talking to my friends who worked in the industry. It wasn’t a bad approach, but after taking a few months to learn some basics and look into code bootcamps, I started developing a more organized strategy.

Often, I have felt adrift in my learning process–not sure of what is most important and what I might be missing completely. But lately, I’ve been getting glimpses of the big picture: what code bootcamp will be like, and more distantly, what working as a programmer will be like. That’s given me some confidence in my approach and helped me use my time more productively.

Here are the strategies for learning to code and preparing for bootcamp admissions that have worked best for me:

  • Using a variety of learning tools to find the ones that work best for me (and to switch between when I need a change in scenery.) I’ve used W3Schools, Codecademy, Udacity, Codewars, Coderbyte, Codefights, and Flatiron’s free lessons on Learn.co, as well as podcasts, blogs, and Twitter.
  • Taking notes on anything that may be useful in the future. I created a .txt document so that I can easily add and search for bits of code. I also define terms, summarize concepts, and paste in websites that I may need to refer back to.
  • Being open to both long and short study sessions. Sometimes, I can get wrapped up in involving code challenges for a couple hours without noticing the time pass, but for tasks that I’m dreading, it’s tough to get motivated to push through them. I try to set aside 20-30 minutes to chip away at tricky or otherwise untempting tasks.
  • Identify recurring concepts and mastering them. Recently, I created a 24 problem “quiz” for myself that covered concepts, such as recursion, that I had encountered but not fully mastered. With help from Google, I solved (and then re-solved) the problems until the solutions came easily to me.
  • Trying to finish a study session on a high note; it’s a morale boost that makes it easier to get back to work later. (That said, if I get stuck on a problem that seems unsolvable, I take a break from it. More than once, I have returned to a coding challenge with fresh eyes and quickly noticed an easily fixable mistake.)

CodeFights

In a followup to my post about CodeWars and Coderbyte (two sites that offer coding practice problems), here are my notes on the latest site I’ve been using: CodeFights. CodeFights has several types of challenges, including quizzes, “Tourneys,” and “Head to Head” competitions, but I’ve been using only the the “Code Bots” feature so far.

I like the setup. Each challenge has three parts: one problem fixing broken code, one problem adding to partially written code, and one problem to solve from scratch. At the end, my scores are matched against a “bot” to see who won. It’s nice having a warmup to the hardest problem at the end, and I liked that I’m pushed to stay focused through three problems. The challenges I have finished so far are comfortably within my ability level, and completing each set unlocks a new (presumably harder? If so, the increase in difficulty is marginal) challenge.

I’ve found it user-friendly and glitch-free so far. Occasionally the instructions for problems are a little unclear.

Codewars vs Coderbyte

For the past two weeks, I have been solving as many practice problems as I can manage in my spare time leading up to coding bootcamp admissions exams. The two sites I’ve mainly been using are Codewars and Coderbyte.

Codewars is a community-driven site that uses some gimmicky terms (“kata” are code challenges completed to achieve “rank”) to make the challenges feel like a special mission, I guess. The two downsides I found with Codewars were that I had trouble getting around at first (the interface is a little busy) and I had some glitches when I tried to submit my answers. The upside is that the challenges are sorted into eight different levels, so you don’t have to work on problems above or below your ability level.

Coderbyte challenges have a straightforward setup with easy, medium, and hard level problems. I have been working on the easy challenges, but have found a big range in difficulty. Some I could solve with only my knowledge from finishing the JavaScript track on Codecademy and a little Googling. Others were way beyond my ability level and I had to look at the provided solution. A very limited number of Coderbyte challenges are free. I invested in the $24 a month for access to more questions and the solutions (though sometimes users had better solutions than the site provided.) The membership fee also gives access to bootcamp study guides, which I found very helpful.

Overall, I’ve mainly stuck with Coderbyte for its reliability and simplicity, but turned to Codewars for a change of pace, when needed.

JavaScript Cheat Sheet Updated

After working through several of CoderByte‘s easy challenge problems, I have added quite a bit to my JavaScript Cheat Sheet. Most additions are built-ins which I have become more familiar with using (such as array.reduce(), array.sort(), and Math.floor() /Math.round() /Math.ceil()). I also added the basics of using regular expressions, which I had not encountered until reviewing CoderByte’s provided challenge solutions.

JavaScript Cheat Sheet_Updated

(p.s. these are my personal notes, not any sort of official guide.)

 

JavaScript Cheat Sheet

Finished Codecademy’s JavaScript course recently, as I’m preparing for bootcamp admissions tests. The similarities between JavaScript and Python (which I used in a Udacity course) were obvious from the start, and of course, the programming fundamentals (for loops! while loops! if/else statements! etc) are the same.

This week I’ve started doing Coderbyte problems, which is certainly putting my new knowledge to the test. I like Coderbyte’s user experience–very clean and straightforward. (Tried Codewars last week and didn’t like the setup quite as much.)

The cheat sheet I created of Javascript basics has come in helpful, especially for double checking my syntax. Here’s a PDF of what I have so far.   JavaScript Cheat Sheet

(p.s. these are my personal notes, not any sort of official guide to JavaScript.)