JavaScript Console
Let us understand how to use the JavaScript Console for debugging and viewing outputs, and learn the most common console methods.
What is the JavaScript Console?
The console is a developer tool built into modern web browsers that helps you:
- See output from your code
- Identify and debug errors
- Run JavaScript directly in real time
How to Open the Console?
Chrome / Edge / Firefox: Right-click on the page → Inspect → Console tab
Or use shortcuts:
- Ctrl + Shift + J (Windows/Linux)
- Cmd + Option + J (Mac)
JavaScript Console Example
The console.log() method is used to print messages to the console.
console.log("Hello from JavaScript!");
console.log(5 + 10); // Outputs 15
Hello from JavaScript!
15
This is useful for checking variable values, function outputs, and debugging your code step by step.
Useful Console Methods
1. console.warn()
Displays a warning (usually highlighted in yellow).
console.warn("This is a warning!");
2. console.error()
Displays an error message (usually red).
console.error("Something went wrong!");
3. console.table()
Displays data (like arrays or objects) in a table format.
let user = { name: "Alice", age: 25 };
console.table(user);
4. Manual JSON Stringify for Clarity
console.log(JSON.stringify(users, null, 2)); // Pretty print with 2-space indentation
5. Use console.dir()
Explore deeply nested objects
console.dir(company);
- console.log() displays objects as-is, often rendering DOM elements with HTML styling.
- console.dir() displays objects as a JavaScript object tree, focusing on properties and structure.
Full Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Console</title>
<script>
console.log("Hello from console.log()");
console.warn("This is just a warning.");
console.error("This is an error message.");
let car = {
brand: "Toyota",
model: "Camry",
year: 2023
};
console.table(car); // View object/table in a table format.
const company = {
name: "TechCorp",
departments: {
engineering: {
head: "Alice",
employees: 50
},
marketing: {
head: "Bob",
employees: 20
}
}
};
console.table(company); // Will flatten only top-level keys
console.dir(company); // fully expandable object tree in the console
console.log(JSON.stringify(company)) // Print nested object as readable string
</script>
</head>
<body>
<h2>Open your browser's Console (F12) to see the results.</h2>
</body>
</html>
You can run this program online and check console in output window: https://codepen.io/pen/
JavaScript Console Methods – Use Cases Summary
Use Case | Console Method |
---|---|
Basic output/debugging | console.log() |
Highlight problems | console.warn() |
Report serious errors | console.error() |
View object/array data in table form | console.table() |
Explore deeply nested objects | console.dir() |
Print full object as readable string | console.log(JSON.stringify(obj)) |
Exercises & Assignments |
---|
No Content Found. |
Interview Questions & Answers |
---|
No Content Found. |