A Quick Guide to Debugging in Ruby and JavaScript
Debugging or identifying problems with your code is an essential skill for being a good developer. It’s not always easy though. If you’re a beginner or just need a refresher, this guide breaks down the basics for the six most common debuggers, three for Ruby and Rails and three for JavaScript.
Ruby/Rails Debugging Tools
Binding.pry
Set up: Make sure you add the gem ‘pry-rails’ in your Gemfile and run bundle install.
What it does: Dropping a binding.pry into your code will pause your code at that point. It stops execution of the code and starts a REPL which allows you to dynamically type Ruby code and evaluate the result.
Byebug
Set up: Version 5.0 of Rails comes with byebug, but if you don’t have it just add gem ‘byebug’ to your Gemfile and run bundle install.
What if does: Like binding.pry, simply drop byebug into your code and your code will pause at that breakpoint allowing you to dig deeper into the code at that point in the application. Byebug has some additional functionality that binding.pry lacks.
Additional functionality:
n => executes the next line of code
s => steps into the next stack of code
c => continues the program until it either concludes or it reaches another breakpoint
l => outputs the source code that is currently being run.
q => this will quit the ByeBug and return back to the program.
Rails Console
What it does: Rails console is an irb session that is built into the Rails environment. Simply type rails c into the terminal to access it. Rails console can be used to test association methods, validations, and check error messages when building a rails app. Or use it like a sandbox to test if something works in Ruby.
JavaScript Frontend Debugging Tools
Debugger
What it does: Dropping a debugger into your JavaScript code sets a breakpoint at which to pause the code (similar to binding.pry and byebug in Ruby). If no debugging functionality is available, this statement has no effect. You can view the breakpoint in Chrome DevTools which I discuss more below.
Console.log()
What it does: Console.log() writes a method to the console.
Examples: If you type console.log(‘hello world’), the string ‘hello world’ will print to the console. Perhaps more helpful is to console log a variable or combination of a string and a variable. Including both a string description and a variable helps you remember what you are console logging. Don’t forget to separate the two with a comma.
const myArray = [‘apple’, ‘kiwi’, ‘banana’]
console.log(‘myArray’, myArray)
Result in console: myArray [‘apple’, ‘kiwi’, ‘banana’]
Chrome DevTools Console
How to access: Press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux, Chrome OS) to open the Console.
What it does: The Chrome DevTools Console gives you a REPL that you can use as a playground to test code, see results of console logs/debuggers, and view error messages.