JavaScript Debugging for Rubyists

A short but sweet translation guide to help Rubyists discover the JavaScript equivalents of common Ruby debugging techniques.

Debugger Breakpoints

# In Ruby
binding.pry
byebug

// In JavaScript
debugger;

When JavaScript encounters the debugger keyword, and your browser Debugger tab is open, execution will pause and the JavaScript source will be shown at the debugger breakpoint.

As with Pry and Byebug, you can examine and interact with the variables available at the paused line using the console (press the Escape key to toggle quick access to the console).

To resume execution, click the play (triangle icon) button found in the Debugger tab.

An alternative to using the debugger keyword is to view the JS source in the Debugger tab and click in the line gutter to set a breakpoint for a specific line of code.

Logging

# In Ruby
puts x.inspect
p x
puts "The value of x is #{x}"
logger.info "The value of x is #{x}"

// In JavaScript
console.log(x);
console.log("The value of x is", x);

Each argument to console.log() will be printed to the browser console. Click on the printed arguments to inspect them more deeply.

A handy feature of console.log() is that it accepts multiple arguments – console.log(x, y, z) is acceptable, and prints the values of x, y, and z to the console.

Pretty Printing

# In Ruby
pp some_obj # Ruby Std-lib PP
ap some_obj # Using awesome_print gem

# In Rails view templates
<%= debug some_obj %>

// In JavaScript
console.dir(someObj);

Try it out by running console.dir(document) in your browser console. Click on the result to dive into the document object further.

Print Stack Trace

# In Ruby
puts caller

// In JavaScript
console.trace();

The stack trace reveals the sequence of function calls that lead to the current line being executed.

Explore

You’ve seen how you can borrow from your Ruby debugging skills to learn how to debug JavaScript more effectively.

Play and click around in the browser dev tools, in particular the Debugger tab, to discover what else is possible.

To find out about more advanced debugging features see the Firefox and Chrome docs from the browser vendors.

Published by Eliot Sykes

I help teams grow their Rails apps and themselves as a Rails consultant and coach for Rails developers.