Debugging

'Debugging' is figuring out why your code isn't working as expected.

This is obviously very important whilst you're learning to code!

Console

We recommend using Chrome for debugging. The chrome debugger has a tab called 'console'.

To open Chrome's console:

If your javascript program had any errors - they'll be shown here along with any 'logging' your program does.

At the bottom of the console there is a box you can type javascript code into. You can use this box to evaluate expressions and see what javascript returns.

Logging to the console in your code

console.log() is a function which prints it's parameter(s) to the console. This allows you to see what's going on with variables in your program as the program runs.

console.log('Program got here!')
'Program got here!'
=> undefined

Note: console.log() actually returns undefined, but before it returns it prints things to the console.

Here we print a const x:

const x = 3
console.log(x)
3 // logs x!
=> undefined // returns undefined

You can (and should) provide multiple arguments to console.log():

const o = {hello: 'world'}
console.log('myObject' , o)
'myObject' {hello: 'world'}
=> undefined // returns undefined

Gotcha: [object Object]

const o = { hello: 'world' }
console.log(`myObject: ${o}`)
'myObject: [object Object]'
=> undefined

If you try and log an object as a string you might run into an issue where javascript instead prints [object Object].

You can get round this by using JSON.stringify(o)

const o = { hello: 'world' }
console.log(`myObject: ${JSON.stringify(o)}`)
'myObject: {"hello":"world"}'
=> undefined

console.log() is massively powerful. I still use console.log() for most debugging I do every day.

Chrome debugger

Chrome also has a more advanced debugger. This allows you to set 'breakpoints' in your code where the program will pause. Chrome will show you the line of code it paused on as well as the values of the variables in the program at the point where it's paused.

The most reliable way to set a breakpoint is by adding a debugger; line to your code.

const x = 1
const y = x + 1
debugger;
const z = x + y - 2

Make sure the chrome console is open before your program runs by opening it and then refreshing the page.