Debugging
The "console" is where you see errors that occur in your code, and you print messages to it for very easy debugging. In Chrome, open "Developer Tools" to access the console. It's a good idea to always keep it open to the console.
If you are using Node.js, the console is what you see when you run your code.
To print a message to the console use console.log()
for simple one-line messages, or console.dir()
to print the contents of an object:
console.log("Code has started");
console.log("Value is: " + state);
console.dir(state);
Printing to the console can be very useful for figuring out what the value of a variable is as the program runs, and whether particular sections of code run when you expect them to run.
Dumping objects
Complex objects don't always print nicely using console.log
- you might get something like: [Object object]
displayed. One way of dealing with this is to stringify the object - that is, to convert it to text, using JSON.stringify()
:
console.log(JSON.stringify(myVariable));
Another option is to try console.table
or console.dir
instead of console.log
.