JavaScript’s console.log is like your trusty notebook during the coding journey – it helps you see what’s happening in your code, debug problems (find and fix errors), and understand how your program works. Think of it as your code’s way of talking to you! If you’re coming from our previous article about JavaScript environments, you’ll find console.log is essential in both browser and Node.js environments.
What is console.log and Why Should You Use It?
Before we dive into coding, let’s understand where to find your console:
- In a web browser:
- Right-click anywhere on your webpage
- Select “Inspect” or press F12
- Click on the “Console” tab
- In Node.js:
- Look at your terminal/command prompt window
- This is where you ran your
node
command
Let’s start with your first console.log:
console.log("Hello, I'm learning JavaScript!");
// Output: Hello, I'm learning JavaScript!
Let’s break this down:
console
is your toolbox for debugging.log()
is a method (a function) that prints information- The message inside quotes is called a “string” (text data)
- The semicolon (;) tells JavaScript this line is complete
Basic Console.log Commands
Let’s start with the fundamentals. Syntax refers to the rules for writing code – like grammar rules in English. The basic syntax of console.log is straightforward:
// 1. Logging text (strings)
console.log("My first JavaScript message");
// Output: My first JavaScript message
// Note: Text always needs quotation marks (" " or ' ')
// 2. Logging numbers
console.log(123);
console.log(3.14);
// Output: 123
// 3.14
// Note: Numbers don't need quotes
// 3. Logging multiple items
console.log("Temperature:", 72, "degrees");
// Output: Temperature: 72 degrees
// Note: Commas separate items and add spaces automatically
// 4. Logging true/false values (booleans)
console.log(true);
console.log(false);
// Output: true
// false
Working with Variables
Variables are like containers that store information in your code. An expression is any code that produces a value. Let’s see how to use console.log with them:
// Creating variables
let userName = "Alex"; // String variable
let userAge = 25; // Number variable
let isStudent = true; // Boolean variable
// Logging variables
console.log(userName);
// Output: Alex
// Note: Don't use quotes when logging variables!
// Logging with labels (recommended)
console.log("User's name:", userName);
console.log("Age:", userAge);
console.log("Student status:", isStudent);
// Output: User's name: Alex
// Age: 25
// Student status: true
// Logging calculations
console.log("Age next year:", userAge + 1);
// Output: Age next year: 26
Pro tip: When logging variables, it’s helpful to label your outputs (like adding a description):
Working with Objects and Arrays
Objects and arrays are ways to store multiple related pieces of information together:
An array is like a numbered list of items
An object is like a container with labeled compartments (called properties)
// Creating an object (a collection of related data)
const user = {
name: "Sarah",
age: 28,
hobbies: ["reading", "coding", "music"]
};
// Logging entire object
console.log(user);
/* Output:
{
name: "Sarah",
age: 28,
hobbies: ["reading", "coding", "music"]
}
*/
// Logging specific properties
console.log("Name:", user.name); // Output: Name: Sarah
console.log("Hobbies:", user.hobbies); // Output: Hobbies: ["reading", "coding", "music"]
// Working with arrays (lists)
const colors = ["red", "green", "blue"];
// Logging array
console.log("Colors:", colors);
// Output: Colors: ["red", "green", "blue"]
// Logging specific array item (counting starts at 0)
console.log("First color:", colors[0]); // Output: First color: red
Advanced Logging Techniques
1. Template Literals (Modern String Formatting)
Template literals are a special way to write strings using backticks (`) that let you embed variables directly:
const name = "John";
const score = 95;
// Using template literals (backticks ` and ${})
console.log(`Player ${name} scored ${score} points`);
// Output: Player John scored 95 points
// Note: Use backtick (`) character, not single quote (')
2. Console.table for Structured Data
When you have a list of similar objects, console.table shows them in a neat table format:
// Array of objects (great for showing data in tables)
const students = [
{name: "Emma", grade: "A", score: 95},
{name: "James", grade: "B", score: 88},
{name: "Mia", grade: "A", score: 92}
];
console.table(students);
/* Output shows a nicely formatted table:
┌─────────┬──────────┬───────┬───────┐
│ (index) │ name │ grade │ score │
├─────────┼──────────┼───────┼───────┤
│ 0 │ 'Emma' │ 'A' │ 95 │
│ 1 │ 'James' │ 'B' │ 88 │
│ 2 │ 'Mia' │ 'A' │ 92 │
└─────────┴──────────┴───────┴───────┘
*/
3. Different Console Methods
// Regular information
console.log("Normal message");
// Warning message (usually yellow)
console.warn("Warning: Battery low!");
// Error message (usually red)
console.error("Error: File not found!");
// Information (similar to log)
console.info("Application started");
Practical Examples
Example 1: Simple Calculator
function calculateTotal(price, quantity) {
// Log input values
console.log("Calculating total for:");
console.log("Price per item:", price);
console.log("Quantity:", quantity);
// Calculate total
const total = price * quantity;
// Log result
console.log("Total amount:", total);
return total;
}
// Using the function
calculateTotal(25, 3);
/* Output:
Calculating total for:
Price per item: 25
Quantity: 3
Total amount: 75
*/
Example 2: Working with Arrays
const shoppingList = ["apples", "bread", "milk"];
// Adding an item
console.log("Original list:", shoppingList);
// Output: Original list: ["apples", "bread", "milk"]
shoppingList.push("eggs");
console.log("After adding eggs:", shoppingList);
// Output: After adding eggs: ["apples", "bread", "milk", "eggs"]
// Removing last item
const removed = shoppingList.pop();
console.log("Removed item:", removed);
console.log("Final list:", shoppingList);
// Output: Removed item: eggs
// Final list: ["apples", "bread", "milk"]
Common Mistakes to Avoid
Mistake 1: Forgetting to Remove Debug Logs
// Bad practice in production code (code that's live on a website)
function calculateTotal(price, quantity) {
console.log("Price:", price); // These logs shouldn't be in the final code
console.log("Quantity:", quantity);
return price * quantity;
}
// Better for production
function calculateTotal(price, quantity) {
return price * quantity; // Clean code without debug logs
}
Mistake 2 :Forgetting Quotes for Strings
// Wrong
console.log(Hello); // Error: Hello is not defined
// Correct
console.log("Hello");
Mistake 3 :Using Quotes for Variables
let name = "Tom";
// Wrong
console.log("name"); // Output: name
// Correct
console.log(name); // Output: Tom
Mistake 4 : Not Labeling Outputs
// Hard to understand
console.log(userAge); // Output: 25
// Better - with context
console.log("User age:", userAge); // Output: User age: 25
Console.log in Different Environments
Browser
// In Chrome/Firefox/Safari
console.log("This appears in browser DevTools");
// Press F12 to see the output
Node.js
// In terminal/command prompt
console.log("This appears in terminal");
// Run with: node yourfile.js
Best Practices
- Use Clear Labels
// Not helpful
console.log(x);
// Better
console.log("User score:", x);
- Group Related Logs
console.group("User Details");
console.log("Name:", userName);
console.log("Age:", userAge);
console.log("Email:", userEmail);
console.groupEnd();
- Remove Debug Logs Before Production
// Development version
function calculate() {
console.log("Calculating..."); // Remove this in production
return result;
}
Conclusion
Console.log is an essential tool in every JavaScript developer’s toolkit. It’s like having a conversation with your code – you ask it questions (through console.log), and it answers by showing you what’s happening inside your program.
Key things to remember:
- Use console.log to see what’s happening in your code
- Always write clear, descriptive messages
- Remove or comment out console.log statements before putting your code live
- Practice using different console methods for different types of information
As you continue learning JavaScript, you’ll find yourself using console.log constantly. Don’t worry if it takes time to get comfortable with it – every programmer starts somewhere!
For more advanced JavaScript tutorials and tips, stay tuned for our next article in the series, where we’ll explore working with JavaScript functions and scope (different areas where variables can be used).
Remember: The console is your window into your code’s execution. Use it wisely, and it will become an invaluable tool in your development process.