JavaScript Errors: They're Trying to Help, Really.

Writing JavaScript is hard. You won't get it right the first time. You'll make silly mistakes or overlook your syntax. Luckily, JavaScript has some helpful error codes that try to tell you what to fix.

For someone who is new to JavaScript, understanding these messages can be tricky. What's the difference between a SyntaxError and a TypeError? What the heck does undefined is not a function mean? Today we take a look at common JavaScript error codes and their fixes.


Javascript error

The stuff of nightmares for new developers. Credit xkcd

Update: Google has improved its exception messages. No more "undefined is not a function".

EvalError

Definition:
Comes up regarding a problem with the global function eval().

Fix:
You should never get this error, because, as a developer, you should never be using the eval() function in any sort of production code ever.

RangeError

Definition:
As the name implies, RangeError comes up when one of your parameters (numeric only) is outside of its specified range.

Fix:
Check your parameters first to make sure you are passing valid numbers to your functions. Then, make sure all of your associations are correct; that your ranges are properly defined with signs and numbers and that your passing the expected parameters to the expected functions.

ReferenceError

Definition:
Comes up when there is an invalid reference in your code.

Fix:
ReferenceError typically returns "someVariable is not defined." It's easy to confuse "not defined," where an object does not have any defintion or assignment at all, and "undefined," which is a blank or empty value. I call this one the "typo error," because its usually human errors that lead to variables not being properly assigned in the code. Take a close look at your spelling and case.

TypeError

Definition:
Returns when an object does not have the proper type

Fix:
TypeError is a sneaky one, because the message doesn't give you a whole lot of information about where the error is occuring. This error typically comes from improper scoping. Consider the following code:

var Game = function () {
    this.startGame();
    this.timer = setTimeout(function() {
        this.stopGame();    // What is "this" referring to here?
    }, 0);
};

Calling the Game() function returns:

 Uncaught TypeError: undefined is not a function

It may take a few looks to realize that the setTimeout function is actually called against the window object, not the Game object. Window does not have a default stopGame function. Coder General contributor Faina Shalts recently wrote an excellent piece that goes more in depth on the 'this' keyword in JavaScript.

SyntaxError

Defintion:
Returns when any single hair of JavaScript syntax is out of place.

Fix:
One of the less-awesome parts of writing JavaScript is the extensive use of curly braces, semi-colons, and parentheses. When functions and variables become nested several layers deep, its easy for developer to lose track. Thankfully, syntax errors have straightforward fixes. Check your closures, spelling, and look for typos, especially of singular/plural named functions and variables.

URIError

Definition:
Returns when a URI passed to JavaScript code is not written properly.

Fix:
URI errors are similar to syntax errors, but specifically for URIs. For example, if you pass a % in a URL, without any characters after it, you'll get an URIError. In JavaScript, % is an escape character. The JavaScript functions that evaluate URIs are expecting characters after, and there are none. Check your URIs to make sure all of the syntax is correct.

Every JavaScript developer has run into errors in his or her code at some point. A good developer is able to learn from seeing error codes and fixing the problems. JavaScript nirvana may well be the ability to look forward to getting errors in your code. No matter what errors you get while writing JavaScript, remember that they're just trying to help. Really.

Anatomy of a Rails Application, Part I: Views

Ruby on Rails is a framework for building web applications that allows developers to create back-end database systems quickly. My favorite part of Rails is that it integrates the visual presentation of back-end data easily. Learning how to control databases in general without any visuals can be tricky, so we'll start today by looking at Rails and setting up these visuals the Rails way. Theses visuals are called "views," and written mostly in HTML, with some special Ruby sauce mixed in. Rails gives us some tools using the Ruby language to beef up what we can do in our views. Let's take a look.

This post is the first of a multi-part series on building a Rails application.

alt Introducing PowerUp, a workout logging web application using Rails, MongoDB, and Bootstrap.

There are many resources available for setting up a Rails application from scratch, such as Daniel Kehoe's excellent book, Michael Hartl's tutorial, and the Rails video lesson series at CodeSchool. This series will jump into writing code on a live application.

PowerUp is an application that allows users to log their workouts. PowerUp's views have to provide a visual interface for the following tasks:

  • Create a new user through a signup form
  • Log in an existing user to the site
  • Edit the user's information
  • Create a new workout log
  • Edit the details of a particular workout log
  • Delete a workout from a user's list of workouts.

Rails knows that, in order for our views to display properly in a browser, the html code must be formatted a ceratin way. Rails takes care of part of this issue for us by providing a default page layout, in which other views of our app will show. This default piece is a file called application.html.erb:

<!DOCTYPE html>  
    <html>
        <head>
            <title>PowerUp</title>
            <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
            <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
            <%= csrf_meta_tags %>
        </head>
        <body>
            <%= yield %>
        </body>    
    </html>

The application.html.erb file gives us all of the doctype, html, head, and body tags without any additional configuration. These nice built-in defaults are a theme of developing applications with Rails. On this page, the <%= yield %> tag is a sort of placeholder. Rails puts whichever view is needed in place of the yield tag, and the resulting page is still clean, seamless HTML. For example, if one of our views consisted of the following code:

<h1>This is an example page</h1>  
<p>I'll show up in place of the yield tag, just watch</p>  

The browser would render this:

<!DOCTYPE html>  
    <html>
        <head>
          <title>PowerUp</title>
          <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
          <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
          <%= csrf_meta_tags %>

        </head>
        <body>

            <h1>This is an example page</h1>
            <p>I show up in place of the yield tag, just watch</p>

        </body> 
    </html>

This example is the most basic way in which Rails keeps our code DRY (Don't Repeat Yourself). The yield tag inserts only code that is changing in the HTML, keeping us from having to write the other page tags over and over for each page that the application renders in the browser.

Another tool that helps developers write DRYer code in Rails is view partials. Partials are code chunks that can be called in as many places in your application as needed. In PowerUp, the form used to create a new workout log and edit existing logs is identical. So we'll write a form partial and save is as _form.html.erb within the views/workouts folder.

First, we'll access the form partial in the new workout view, with some Bootstrap styling, like so:

<div class="col-sm-4 col-sm-offset-4">  
    <h1>Edit</h1>
    <%= render "workouts/form" %>
</div>  

Notice how the render calls the 'form' partial from the 'workout' folder. Saving the partial with this specific file path is important. It is likely that there will be other forms in other parts of your Rails application, and the only way to distinguish them when using the render tag is by specifying which folder in which to access the partial. The render tag helps keep code DRY by allowing changes to a single file to be accessed throughout the application.

Having DRY code is awesome and all, but what if we want smart code as well? What if I want to provide PowerUp users links to their profile and log out, but only when they are logged in? Rails gives us a way to do change content based on certain conditions by allowing Ruby code in our views.

First is our navbar links when a user is not logged in:

alt No user logged in, static links.

Here's the code for static links:

<li><%= link_to "Log In", new_session_path %></li>  
<li><%= link_to "Sign Up", new_user_path %></li>  

Pretty straighforward, but these links will always stay the same. Not useful when a user is logged in. We want the user to have access to these links:

alt User logged in, dynamic links

Rails lets us write Ruby code into our views. Let's use an if statement to check if a user is logged in, and show the appropriate links based on this check:

<% if logged_in? %>  
        <li class="active"><%= link_to "Welcome, #{current_user.name}!", user_path(current_user) %> </li>
        <li><%= link_to "Profile", user_path(current_user) %> </li>
        <li><%= link_to 'Log Out', logout_path, method: :delete %></li>
    <% else %>
        <li><%= link_to "Log In", new_session_path %></li>
        <li><%= link_to "Sign Up", new_user_path %></li>
<% end %>  

Now our navbar links will change based on the user's needs. This dynamic content concept can be used in many different ways; error messages, vote/comment counters, and other permission-based content restrictions.

Rails gives developers a few methods for presenting data and information in a flexible way. Yield tags, partials, and even straigh Ruby code are all tools that developers can use to build attractive and useful views in their Rails applications. Try some of these techniques in your next app and see what you can build.

Convert Numbers into Words in Ruby

Part of any introduction to a new programming language should include code challenges. Code challenges are thought exercises of varying levels of complexity designed to apply syntax and convention of a new language to working code. These challenges come in many flavors, from simple type conversions to full logic frameworks. There are several great resources for such challenges, including CodeEval, Project Euler, CodeWars, and the more-involved CodeKatas. Most of these challenges can be tackled in any programming language. Today we take a look Ruby.

How humans learn to count. Does not work for computers.

The Challenge

Consider the following challenge: Write a Ruby method that takes an integer between 1 and 999 inclusive, and returns a string of English words that is the equivalent of that number. For example:

number_to_word(4)   #= 'four'  
number_to_word(13)  #= 'thirteen'  
number_to_word(25)  #= 'twenty five'  
number_to_word(60)  #= 'sixty'  
number_to_word(123) #= 'one hundred twenty three'  
number_to_word(987) #= 'nine hundred eighty seven'  

The human brain can do this conversion very easily (remember writing checks?). The challenge comes from writing the logic in code that a computer will understand. Let's begin by breaking down the challenge into parts.

Where to start? The syntax

For anyone with JavaScript experience, Ruby syntax is often easy to pick up. Many of the structure conventions are simplified in Ruby, leading to leaner, reads-like-English code.

Ruby organizes code into classes and methods. A Ruby class for our challenge is set up like this:

class NumberToWord  
  # lots of code goes here
end  

Within this class, variables and methods are defined like this:

def a_ruby_variable  
  # this is a varible definition
end

def a_ruby_method  
  # this is a method (aka function) definition
end  

Note how variables and methods have similar defintion syntax. This simplicity means there are fewer opportunities for syntax errors. Also note that Ruby uses snake casing naming conventions for variables, methods, and file names.

Now that we have a structure, let's start filling it in with some code.

What is unique? What is reused?

One of the tenets of using object-oriented programming languages like JavaScript and Ruby is constructing code that can easily be reused if needed. Object-oriented nirvana comes from code that completely separates out repeated parts, leaving only unique pieces of code.

In our challenge, the unique pieces are the strings for certain numbers in our range. These include the numbers 1 through 20 ('one', 'two', 'fourteen', 'twenty', etc), and the "decades" ('thirty', 'forty', 'fifty', etc). Our method should return these numbers explicitly, as they cannot be derived from other information provided. What we also see is that these numbers will be reused as well. The number 491 will include the strings 'four', 'ninety', and 'one'. Our method will return these strings in other numbers.

Let's set up a Ruby hash to store these unique strings:

def number_words  
  @number_words = {
    90 => "ninety",   80 => "eighty",   70 => "seventy",
    60 => "sixty",    50 => "fifty",    40 => "forty",
    30 => "thirty",   20 => "twenty",   19 => "nineteen",
    18 => "eighteen", 17 => "seventeen",16 => "sixteen",
    15 => "fifteen",  14 => "fourteen", 13 => "thirteen",
    12 => "twelve",   11 => "eleven",   10 => "ten",
    9  => "nine",     8  => "eight",    7  => "seven",
    6  => "six",      5  => "five",     4  => "four",
    3  => "three",    2  => "two",      1  => "one",
  }
end  

We will use the keys in our hash to return these strings when needed. Now let's look at the method.

Methods, if/else statements, and modulos

We have three scenarios for the parameter passed to our method. The number we get will be:

  • A number defined in our number_words hash,
  • a two-digit number not defined in the hash or,
  • a three-digit number.

An if/else statement within our method will allow us to run different code for each of these possible scenarios. This is one way to set up the code:

def convert(number)  
  # for unique numbers, returns from hash
  if number_words.has_key?(number)
    # lots of code here

  # for all three digit numbers
  elsif (100..1000).include?(number)
    # lots more code here

  # for two digit numbers not already in hash
  else
    # guess what? more code here
  end
end  

Our first scenario is pretty easy to define:

# returns from hash for unique numbers
if number_words.has_key?(number)  
  number_words[number]

Writing code for our three-digit numbers in the second position will show us some code that is reusable in the two digit number position:

# for all three digit numbers
elsif (100..1000).include?(number)  
  [ number_words[number / 100], 
    "hundred", 
    number_words[number - ((number / 100) * 100) - (number % 10)], 
    number_words[number % 10] 
  ].join(" ").strip

There is a lot going on here. Let's unpack this section a bit.

  • Check if the parameter number is in the range between 100 and 1000 exclusive (aka all three-digit numbers)
  • Create an array of each string needed to spell out the number in words; the hundreds digit (pulled from our hash), the string 'hundreds', the tens digit (using some modulo gymnastics to pull from the hash again), and the single digit.
  • Create a single string and insert spaces using the join method. Eliminate trailing whitespace with the strip method.

Finally we add code for two-digit numbers not already in the hash. Notice how this piece is similar to the previous section:

else  
  [ number_words[number - (number % 10)], 
    number_words[number % 10]
  ].join(" ")

Here's the complete code for our method:

class NumberToWord  
  # hash for number with unique word equivalents
  def number_words
    @number_words = {
      90 => "ninety",   80 => "eighty",   70 => "seventy",
      60 => "sixty",    50 => "fifty",    40 => "forty",
      30 => "thirty",   20 => "twenty",   19 => "nineteen",
      18 => "eighteen", 17 => "seventeen",16 => "sixteen",
      15 => "fifteen",  14 => "fourteen", 13 => "thirteen",
      12 => "twelve",   11 => "eleven",   10 => "ten",
      9  => "nine",     8  => "eight",    7  => "seven",
      6  => "six",      5  => "five",     4  => "four",
      3  => "three",    2  => "two",      1  => "one",
    }
  end

  # function for converting numbers to words
  def convert(number)        
    # returns from hash for unique numbers
    if number_words.has_key?(number)
      number_words[number]
    # for all three digit numbers
    elsif (100..1000).include?(number)
      [ number_words[number / 100], 
        "hundred", 
        number_words[number - ((number / 100) * 100) - (number % 10)], 
        number_words[number % 10] 
      ].join(" ").strip
    # for two digit numbers not already in hash
    else
      [ number_words[number - (number % 10)], 
        number_words[number % 10]
      ].join(" ")
    end
  end
end  

This code is pretty good. It passes most cases without a hitch. As with most code, there is room for improvement. We could add some input validation (making sure the number is a number, doesn't start with a zero, isn't a string, etc). There are edge cases where a three-digit number with a zero (ie 907 or 230) will add extra whitespace within the string. Refactoring gets easier and easier when we get more comfortable with a new language.

Completing code challenges is not about writing world-changing code. Challenges are designed to do just that; challenge your knowledge. Completing as many challenges as you can, especially when learning a new programming language, is a surefire way to improve your skills quickly.

Strategies for Effective Pair Programming

Pair programming has been around for ages, and has many advantages for programmers in both in production and learning environments. Pairing can scale your programming time and result in faster, cleaner code. Pairing often creates cross-polination of ideas and experiences between programmers. Many development companies, such as Pivotal Labs, Hashrocket, and Braintree find pairing so effective that it is the default model of working on production code. Modern technology even allows for remote pairing, further expanding the impact of pairing around the world.

Ken Block Scares

An example of ineffective pairing

While pairing is almost universally considered helpful in writting code, having a methodical approach to pair programming is vital in getting the best results. Here are some do's and don'ts:

How to pair effectively

There are two systems that have worked particularly well for me when it comes to maximizing pairing. These are often called different names, but the concepts remain.

The driver-navigator system

The classic way that most people think of pair programming is splitting the pair into two distinct roles. These roles organize the logistics of how the code will be written. The "driver" is typically writing all of the actual code, while the "navigator" role combines directing, supporting, debugging, and generally being an extra set of eyes for the driver. The driver is unencumbered with juggling the non-typing parts of writing code, while the navigator can better identify issues that come up in his code. Both roles are actively engaged in coding while not getting bogged down or distracted.

This arrangement is particularly helpful in pairs of differing skill levels. A more experienced coder navigating for a greener driver is among the highest impact methods for teaching code available today.

The meet-you-at-the-finish-line system

This system is the opposite from driver-navigator, and is really a nontraditional pairing technique. In this system, pairs start working independently on the same code for an agreed upon amount of time, then reconvene to compare notes and integrate their work.

It is important to emphasize that the finish-line system is NOT a race. The value of finish-line pairing comes from the diversity of experience, approach and opinion of the two coders. Coding a quick website with some simple JavaScript? A visually oriented coder may begin with layout and interface, while her structurally inclined pair may start on logic and event handling. Coming back together and comparing notes will generate discussion that looks like this:

  • How did you arrange the layout?
  • What did you call that button/link/area/background/selector?
  • How do we get all of this stuff to talk to each other?

Getting to the last question is the apex of finsih-line pairing. The coders now focus on putting code together, identify missing pieces, and completing code together. Switching to driver-navigator mode at this point can accelerate the proces, and is natural transition to recharge and reset for another session of coding.

How not to pair

The keeping-up-with-the-Jones way

Everyone say this three times: Pairing is NOT racing. Got it? Good. It cannot be emphasized enough that pairing is about teamwork, not competition. Especially in newer coders, the urge to sneak looks an compare progress is tempting, but doing it enough will result unproductive work. Pairing using a single machine can eliminate this problem from you pairing sessions.

The why-don't-you-know-this-already way

Good pairing creates an open and safe environment for two programmers to share ideas and collaborate. Both programmers should feel comfortable enough to ask questions and approach unfamiliar topics without getting an eyeroll in response. Both coders in the pair are responsibile for embracing differences of opinion and experience while keeping the pair moving toward the common goal. Newer programmers can still teach more experienced programmers, whether its through a focus on fundamentals or a fresh perspective on old techniques.

Pair often, pair better

Pair programming has long been considered a valuable tool for programmers to write code quickly and more cleanly. Recent research has suggested that gains from pairing are repeatable and significant, which lends even more credibility to the process. As a newer coder, I have found pairing with both other newer coders and more experienced professionals has been hugely helpful in learning how to code. Pivotal Labs' Farhan Thawar puts it nicely thus:

So to recap, you should only pair program when you want intensely focused, effective engineers to write high-quality software, to learn from each other and to share domain knowledge.

For everything else, silo program all day…

Welcome to Ghost

Editor's note: This article is a repost of the default article that comes with the Ghost platform.

You're live! Nice. We've put together a little post to introduce you to the Ghost editor and get you started. You can manage your content by signing in to the admin area at <your blog URL>/ghost/. When you arrive, you can select this post from a list on the left and see a preview of it on the right. Click the little pencil icon at the top of the preview to edit this post and read the next section!

John O'Nolan, founder at Ghost.

Getting Started

Ghost uses something called Markdown for writing. Essentially, it's a shorthand way to manage your post formatting as you write!

Writing in Markdown is really easy. In the left hand panel of Ghost, you simply write as you normally would. Where appropriate, you can use shortcuts to style your content. For example, a list:

  • Item number one
  • Item number two
    • A nested item
  • A final item

or with numbers!

  1. Remember to buy some milk
  2. Drink the milk
  3. Tweet that I remembered to buy the milk, and drank it

Want to link to a source? No problem. If you paste in a URL, like http://ghost.org - it'll automatically be linked up. But if you want to customise your anchor text, you can do that too! Here's a link to the Ghost website. Neat.

What about Images?

Images work too! Already know the URL of the image you want to include in your article? Simply paste it in like this to make it show up:

The Ghost Logo

Not sure which image you want to use yet? That's ok too. Leave yourself a descriptive placeholder and keep writing. Come back later and drag and drop the image in to upload:

Quoting

Sometimes a link isn't enough, you want to quote someone on what they've said. It was probably very wisdomous. Is wisdomous a word? Find out in a future release when we introduce spellcheck! For now - it's definitely a word.

Wisdomous - it's definitely a word.

Working with Code

Got a streak of geek? We've got you covered there, too. You can write inline <code> blocks really easily with back ticks. Want to show off something more comprehensive? 4 spaces of indentation gets you there.

.awesome-thing {
    display: block;
    width: 100%;
}

Ready for a Break?

Throw 3 or more dashes down on any new line and you've got yourself a fancy new divider. Aw yeah.


Advanced Usage

There's one fantastic secret about Markdown. If you want, you can write plain old HTML and it'll still work! Very flexible.

That should be enough to get you started. Have fun - and let us know what you think :)

A New Beginning: Welcome to Coder General

Famous words are usually famous last words, or famous first words. Words that came at a famous moment, or that were spoken by certain people are remembered as famous. Fame rarely comes from everyday words like "remember to get milk, dear" or “that’ll be $3.75, sir”. Those lack the gravitas needed to withstand the test of time. However, the most famous words I’ll ever remember would be a bit plain for most:

“Welcome to General Assembly. Let’s get started.”

Just six weeks ago, I drove nearly the entire length of US Interstate 40 to join an talented and diverse group of ready to put sweat equity and long hours into making a radical change in their lives. We all joined one of the top coding schools in the world for a reason. General Assembly's Web Development Immersive is among the most intense programs around, and they've been producing great coders long than anyone else. I am floored by the sheer drive of my classmates. Even after putting in nearly 50 hours in the first five days, I am unwaveringly confident that any task, technology, or CSS selector is conquerable.

Coder General is a place where our cohort will share stories about the good and less good of learning code and growing together. Maybe you’ll learn some code here that you didn’t know before. Maybe you’ll laugh. Maybe you’ll think we’ll never become good programmers in 12 weeks. Time will certainly tell.

Coder General. Famous words for a famous time. Welcome, let’s get started.