Code Tracing in JavaScript
NOTE
In the video alert()
was used for code tracing, it is now better to use the console methods such as console.log()
.
Code tracing is a basic, yet effective way to debugging your code, which involves adding messages throughout the code to trace the path the computer works through the program. While code tracing can be rudimentary and somewhat time consuming, it does not require any special tools and has a low learning curve.
The following code has a bug in it.
function first () {
second()
}
function second () {
third()
}
function third () {
forth()
}
function fourth () {
headline.textContent = 'You clicked the headline!'
}
headline.addEventListener('click', function () {
first()
})
We can use the console.log()
method to trace through the code to find the error.
function first () {
console.log('Calling second()')
second()
}
function second () {
console.log('Calling third()')
third()
}
function third () {
console.log('Calling fourth()')
forth()
}
function fourth () {
console.log('Updating headline')
headline.textContent = 'You clicked the headline!'
}
headline.addEventListener('click', function () {
console.log('Calling first()')
first()
console.log('Called first()')
})
As the browser works through the JavaScript, our trace messages will be displayed in the console. Reviewing the console we can see the path that was taken and where the code stopped.