Using the JavaScript Console
When you’re learning JavaScript, one of the best tools you’ll use is the console. It’s like a mini notepad that shows what’s happening in your code. You can use it to display messages, track variables, and catch problems while writing or testing your code. The console is built into every modern browser and helps you understand what your code is doing behind the scenes.
console.log(), console.error(), console.table()
The console.log()
method is the most common way to show something in the console. It prints messages, numbers, or anything else you want to check.
console.log('Hello, JavaScript!');
You can also log variables:
let name = 'Alex';
console.log(name);
If something goes wrong in your code, console.error()
helps you show an error in red text. It doesn't stop your program, but it makes the problem easier to see.
console.error('Something went wrong!');
When you’re working with arrays or objects, console.table()
shows the data in a clean table format. This is super useful for seeing things clearly.
let users = [
{ name: 'Sam', age: 25 },
{ name: 'Tina', age: 30 }
];
console.table(users);
This will print a nice table instead of a messy block of data.
Debugging with console output
Sometimes, your code won’t do what you expect. This is where debugging comes in. Debugging means finding and fixing errors. The console helps by showing you what's going on.
You can insert console.log()
statements in different parts of your code to follow what’s happening step by step.
let total = 5 + 10;
console.log('Total is:', total);
This way, if something doesn’t look right, you’ll know exactly where it happened.
Using the console doesn't just help with errors—it also helps you test small parts of your code quickly. Just open your browser’s Developer Tools (usually by pressing F12 or right-clicking and selecting "Inspect") and go to the “Console” tab. You can even write and run code directly there to test ideas.