11.4 Advanced console.log

Advanced console.log (15 mins)

  1. Introduction to Advanced console.log:

    • While console.log() is commonly used for simple debugging (like logging strings or numbers), it can also be used to output more complex and formatted information, which makes debugging more effective.

  2. Using Placeholders for String Formatting:

    • You can format your output by using placeholders (%s, %d, %c) inside the string, followed by variables that will replace these placeholders:

      • %s: String placeholder.

      • %d: Number placeholder.

      • %c: CSS style placeholder.

    Example:

    let name = "Adil";
    let age = 25;
    console.log("Name: %s, Age: %d", name, age);  // Outputs: Name: Alice, Age: 25
  3. Logging Objects and Arrays:

    • console.log() can be used to print the contents of objects and arrays, allowing you to inspect complex data structures.

    • Objects and arrays are printed in a readable format, allowing you to explore nested structures.

    Example:

    let user = { name: "Adil", age: 25, city: "Bishkek" };
    console.log(user);  // Outputs the entire object

    Logging Arrays:

    let fruits = ["Apple", "Banana", "Cherry"];
    console.log(fruits);  // Outputs the array: ["Apple", "Banana", "Cherry"]
  4. Styled console.log() with CSS:

    • You can apply CSS styles to the output in the console using the %c placeholder. This is helpful when you want to visually differentiate logs (for example, when you want to highlight important logs).

    Example:

    console.log("%cThis is a styled log!", "color: blue; font-size: 20px; font-weight: bold;");
  5. Grouping Logs with console.group() and console.groupEnd():

    • These functions allow you to group related log messages together, making debugging more structured.

    • Each group can be expanded or collapsed in the console for easier navigation through logs.

    Example:

    console.group("User Information");
    console.log("Name: Adil");
    console.log("Age: 25");
    console.log("City: Bishkek");
    console.groupEnd();
  6. Other Useful console Methods:

    • console.error(): Outputs an error message in red to help you identify critical issues.

      console.error("This is an error message!");
    • console.warn(): Outputs a warning message.

      console.warn("This is a warning message!");
    • console.table(): Displays arrays or objects in a table format, which is useful for quickly inspecting data.

      let people = [
        { name: "Adil", age: 25 },
        { name: "Bob", age: 30 }
      ];
      console.table(people);  // Outputs a table with people information

Student Activity (15 mins):

Objective: Students will practice using advanced logging techniques in the console, including formatted logging, object and array logging, styling logs with CSS, and using groups and tables.

Instructions:

  1. Create an HTML file (e.g., advanced_console.html) with embedded JavaScript.

    Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Advanced Console Logging</title>
    </head>
    <body>
      <h1>Check the Console for Advanced Logging</h1>
      
      <script>
        // 1. Using placeholders for formatting
        let userName = "Adil";
        let userAge = 25;
        console.log("User: %s, Age: %d", userName, userAge);  // Outputs: User: Alice, Age: 25
    
        // 2. Logging objects and arrays
        let user = { name: "Adil", age: 25, city: "Bishkek" };
        console.log("User Object:", user);
    
        let fruits = ["Apple", "Banana", "Cherry"];
        console.log("Fruits Array:", fruits);
    
        // 3. Styled logging with CSS
        console.log("%cThis is a styled message!", "color: green; font-size: 16px;");
    
        // 4. Grouping console logs
        console.group("User Details");
        console.log("Name: Adil");
        console.log("Age: 25");
        console.log("City: Bishkek");
        console.groupEnd();
    
        // 5. Using console.table to log arrays as a table
        let people = [
          { name: "Adil", age: 25 },
          { name: "Bob", age: 30 },
          { name: "Charlie", age: 35 }
        ];
        console.table(people);
    
        // 6. Using console.error and console.warn
        console.error("This is an error message.");
        console.warn("This is a warning message.");
      </script>
    </body>
    </html>
  2. Run the file in a browser:

    • Open the HTML file in a browser.

    • Open the Developer Tools (F12 or right-click and select Inspect), then go to the Console tab to see the different log outputs.

  3. Activity:

    • Step 1: Inspect the formatted output of the user information using %s and %d placeholders.

    • Step 2: Look at how objects and arrays are logged in the console.

    • Step 3: Try changing the CSS styling in the log (e.g., change the color or size).

    • Step 4: Expand and collapse the grouped log messages.

    • Step 5: Review the table format generated by console.table() to see how structured data can be easily inspected.

    • Step 6: Observe how console.error() and console.warn() format error and warning messages.

Follow-up Questions:

  1. How does using placeholders improve your logging output?

  2. What are the benefits of logging objects and arrays in a structured format like console.table()?

  3. How can styled console messages (with %c) help in debugging larger projects?

  4. When would you use console.group() and console.groupEnd() in a real-world scenario?

Expected Outcome:

Students will gain an understanding of advanced console.log() features such as formatting, logging complex data types (objects, arrays), styled logs, and using additional methods like console.group(), console.table(), and console.error(). This will make debugging and organizing logs easier in more complex JavaScript projects.

Last updated