JavaScript - Console.log()

-

Basic Syntax

To use console.log(), you need to call the function and pass the data you want to log as arguments. The most basic way to use console.log() is to pass a single argument, which can be a string, number, boolean, object, or array.

Example: Logging different data types

console.log("Hello, World!");
console.log(42);
console.log(true);
console.log({ name: "John", age: 30 });
console.log([1, 2, 3, 4, 5]);

You can also pass multiple arguments to console.log() by separating them with commas. When you do this, the console will output each argument in order, with a space between them.

Example: Logging multiple arguments

console.log("Hello", "World", "!");
console.log("The answer is", 42);
console.log("Is this true?", true);

Another useful feature of console.log() is string substitution. You can use the %s placeholder in your string to insert a variable value into the output.

Example: String substitution

const name = "John";
const age = 30;
console.log("My name is %s and I am %s years old.", name, age);

Using console.log() with these basic techniques can help you inspect your code's behavior and spot any issues that may arise.

Logging Different Data Types

console.log() can handle different data types, making it a tool for logging information in your JavaScript code.

Example: Logging strings

console.log("This is a simple string.");
console.log("You can log" + " concatenated strings too.");

Example: Logging numbers

console.log(42);
console.log(3.14159);
console.log(-100);

Example: Logging booleans

console.log(true);
console.log(false);
console.log(2 > 1);
console.log(2 < 1);

Example: Logging objects

const person = {
  name: "John",
  age: 30,
  city: "New York"
};
console.log(person);

Example: Logging arrays

const fruits = ["apple", "banana", "orange"];
console.log(fruits);

const numbers = [1, 2, 3, 4, 5];
console.log(numbers);

By logging different data types with console.log(), you can quickly inspect the values of your variables and the state of your program at various points in your code.

Formatting Output

console.log() lets you format the output using CSS-style formatting, apply colors and styles to logged messages, and create tables and groups in the console.

To apply CSS-style formatting, use the %c directive followed by the CSS rules you want to apply. The CSS rules should be provided as the second argument to console.log().

Example: Applying CSS-style formatting

console.log("%cThis is a styled message", "color: blue; font-size: 20px; font-weight: bold;");
console.log("%cMultiple styles can be applied", "color: red; background-color: yellow; padding: 5px;");

You can also apply colors and styles to specific parts of the logged message using the %c directive multiple times within the same string.

Example: Applying styles to specific parts

console.log("This is a %cblue%c and %cbold%c message.", "color: blue;", "", "font-weight: bold;", "");

console.log() also lets you create tables and groups in the console for better organization and readability of the logged data.

To create a table, use the console.table() method and pass an array or object as the argument. This will display the data in a tabular format.

Example: Creating tables

const products = [
  { name: "Product 1", price: 10 },
  { name: "Product 2", price: 20 },
  { name: "Product 3", price: 30 }
];
console.table(products);

To create groups, use the console.group() and console.groupEnd() methods to group related log messages together. You can also nest groups within each other.

Example: Creating groups

console.group("User Details");
console.log("Name: John Doe");
console.log("Age: 30");

console.group("Address");
console.log("Street: 123 Main St");
console.log("City: New York");
console.groupEnd();

console.groupEnd();

By using CSS-style formatting, applying colors and styles, and creating tables and groups, you can make your logged output more visually appealing and easier to read and understand.

Debugging with Console.log()

console.log() is a helpful tool for debugging JavaScript code. By logging variables, objects, and messages at different points in your code, you can track the flow of your program and spot any errors or issues.

One common use of console.log() for debugging is to track variable values as your code runs. By logging variables at key points in your program, you can see how their values change over time and make sure they are being updated as expected.

Example: Tracking Variable Values

let count = 0;
console.log("Count before the loop:", count);

for (let i = 0; i < 5; i++) {
  count++;
  console.log("Count inside the loop:", count);
}

console.log("Count after the loop:", count);

Another way to use console.log() for debugging is to log messages that indicate when certain parts of your code are being run. This can help you identify which parts of your code are executed and in what order.

Example: Logging Messages

function multiply(a, b) {
  console.log("Entering multiply function");
  console.log("Arguments: a =", a, "b =", b);

  const result = a * b;
  console.log("Result:", result);

  console.log("Exiting multiply function");
  return result;
}

const total = multiply(5, 7);
console.log("Total:", total);

When debugging, you can also use console.log() to log error messages when something goes wrong in your code. By logging errors with information about what caused them, you can quickly identify and fix issues in your code.

Example: Logging Error Messages

function divide(a, b) {
  if (b === 0) {
    console.log("Error: Division by zero");
    return null;
  }
  return a / b;
}

console.log(divide(10, 2));
console.log(divide(10, 0));