JavaScript — console.log and debugger
On my coding journey through Javascript (JS), one of the most important tools that helped me was how to use and make use of console.log
and debugger
.
console.log
is the JS equivalent of puts/print/p from ruby and ruby on rails.
Similar to binding.pry
for ruby and byebug
for ruby on rails, using debugger
in your javascript file will allow you to test, find, and reduce bugs (errors) in your code. The earlier you begin to use it, the faster your progress will be in learning JS.
In your browser, on your webpage (i.e. index.html), open up your console with the key combination of Ctrl + Shift + J on PC, or Option + ⌘ + J on MAC. You should see something like this.
If your code is something like the below
<!DOCTYPE html>
<html>
<body><h1>My First Web Page</h1><script>
a = 500;
b = 200;
c = a + b;
console.log(c);
</script></body>
</html>
your console should show the following, with the value of “c” printed out on the console
you can put console.log
anywhere in your code to help see what a value is or to see if your code has reached a certain point when you are interacting with the website.
debugger
is like a pause or breakpoint in your code. For example, the below code has a debugger bolded in the middle of its code.
<!DOCTYPE html>
<html>
<head>
</head><body><p id=”demo”></p><p>With the debugger turned on, the code below should stop executing before it executes the third line.</p><script>
a = 500;
b = 200;
debugger;
c = a + b;</script></body>
</html>
When you run the code your console will display the following.
The debugger
lets us stop code execution and inspect any variables, values, arrays, etc. In this instance, you can see that I can see the value of “a” is 500 and the value of “b” is 200. You can even type in the next line of code to see if you get an error!
I personally like to use debugger
to find out the correct way to call my variables or values when I am using querySelector and setting const values or even function calls. The earlier you start using these tools the more power you will have with creating bug-free code in JS.