Logging is the practice of printing out useful information that helps you understand what your program is doing. It’s one of the simplest but most powerful tools for debugging, learning, and tracking your application’s behavior.
Whenever you're unsure what your code is doing — or why something is breaking — logs act like a flashlight showing you what's happening step by step.
Logs help you:
Without logging, you're “programming in the dark.”
console.log("Function started");
console.log("User age:", age);
console.log("Calculating total price...");
💡 Logging is often the first step in solving ANY debugging problem.
This is the most common and simplest way to create logs:
console.log("Hello!");
console.log("The value of x is", x);
console.log(user);
But logging is more powerful when used intentionally, not randomly.
JavaScript provides different log methods to express the importance of a message:
Used for normal, everyday information.
console.log("App started");
Used when something is not broken but could be a problem.
console.warn("User email is missing. Using default value.");
Used when something is broken or failed.
console.error("Failed to load data from API");
Similar to log but semantically clearer.
console.info("User logged in:", username);
Useful for detailed debug information.
console.debug("Loop iteration:", i);
💡 Using the right level makes logs more meaningful and easier to filter.
You can log values directly:
console.log(score);
console.log(isLoggedIn);
console.warn(user);
Or label them for clarity:
console.log("Current score:", score);
console.log("User data:", user);
Logging objects is extremely useful for inspection.
When debugging a function, logs help you track:
Example:
function calculateTotal(cart) {
console.log("calculateTotal called with:", cart);
let total = 0;
for (const item of cart) {
console.log("Adding item:", item);
total += item.price;
}
console.log("Final total:", total);
return total;
}
💡 Logs should tell a story: what is happening, in what order, and with what values.
Bad:
console.log("x");
Good:
console.log("Current x value:", x);
Oversharing logs:
Use logs with intention.
Temporary logs should be deleted:
❌ during production
❌ inside loops in final version
❌ inside sensitive areas (passwords, tokens!)
if (!user) {
console.error("User object missing:", user);
}
⚠️ Never log sensitive information like passwords, tokens, or credit card numbers.
console.log("Starting save process...");
console.log("Saving user:", user.id);
console.log("Process completed.");
if (age < 18) {
console.warn("User is under 18. Access denied.");
}
for (let i = 0; i < items.length; i++) {
console.debug("Loop index:", i, "Item:", items[i]);
}
if (!email) {
console.error("Email is undefined:", email);
}
Often makes debugging harder.
Slows the program down.