⬅ Previous Topic
try, catch, finally in JavaScriptNext Topic ⮕
JavaScript Browser APIs⬅ Previous Topic
try, catch, finally in JavaScriptNext Topic ⮕
JavaScript Browser APIsThe console
object in JavaScript provides access to the browser's debugging console. It includes methods that help developers output messages, warnings, errors, and even structured data like tables.
This is the most commonly used method to print messages or variables to the console.
let user = "Alice";
console.log("Hello", user); // Outputs a string and a variable
Hello Alice
Use this method to display error messages. It helps you highlight where something went wrong in your code.
console.error("Something went wrong!");
Something went wrong!
This displays a warning message without stopping the script execution. It’s useful for highlighting potential issues.
console.warn("This might be deprecated soon.");
This might be deprecated soon.
Displays tabular data in a neat table format. Useful when debugging arrays of objects.
let users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
];
console.table(users);
(index) | name | age --------------------- 0 | Alice | 25 1 | Bob | 30
These methods group related messages together, making the console output cleaner and more readable.
console.group("User Info");
console.log("Name: Alice");
console.log("Age: 25");
console.groupEnd();
▶ User Info Name: Alice Age: 25
Measure the time taken by a block of code to execute.
console.time("loop");
for (let i = 0; i < 1000000; i++) {}
console.timeEnd("loop");
loop: 2.345ms
Every modern browser comes with built-in developer tools (DevTools). Press F12
or Ctrl+Shift+I
to open it. Here's how to debug effectively:
Breakpoints pause the execution of JavaScript code at a specific line. This allows you to inspect variables and the call stack.
In DevTools, you can add expressions to watch their values at runtime. The Call Stack shows the nested function calls that led to the current point in code.
These controls let you move through the code line-by-line while debugging:
Q: Why use console.table()
instead of console.log()
?
A: console.table()
is ideal for debugging structured data like arrays of objects. It makes it easier to compare rows visually.
Use debugger;
in your JavaScript code to automatically trigger DevTools and pause execution.
function multiply(a, b) {
debugger;
return a * b;
}
multiply(2, 3);
This will pause the script when run in the browser and open DevTools if available.
⬅ Previous Topic
try, catch, finally in JavaScriptNext Topic ⮕
JavaScript Browser APIsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.