What is console.log() in JavaScript?

Key takeaways:

  • The console.log() method is mainly used for debugging, tracking function outputs, and visualizing data structures in the browser’s console.

  • It directly prints arguments, such as strings, objects, or variables, to the console.

  • It helps with debugging, performance monitoring, tracking events, and inspecting DOM elements.

  • As a good practice, remove unnecessary logs after debugging, use clear messages, and be cautious when leaving logs in production code.

As developers, it’s crucial to track the flow of our code and see how values change during execution. Instead of guessing what went wrong or simply staring at the code, we can log values, function outputs, and even entire objects to the console using console.log().

The console.log() method allows us to:

  • Debug code: It helps us track errors and understand how our program behaves.

  • Test outputs: We can see what values functions calculate or return.

  • Visualize the data: It shows us what data structures like arrays or objects look like at runtime.

Let’s explore how console.log() works and how to utilize it effectively.

What is the console.log() method?

At its core, console.log() is a method that prints any argument passed to it directly to the browser’s console. It can be used to write JavaScript object(s), a JavaScript string with or without substitution strings, or primitive values such as integers and floats. This allows us to visualize information during execution, which is particularly useful when finding bugs in our code.

Syntax

The syntax for console.log() is shown below:

console.log(message);

In the above syntax:

  • console: It is an object that provides access to the browser’s debugging console.

  • log(): It is a method that outputs a message to the console.

  • message: This can be an object(s), string, or a primitive data type.

How does console.log() work?

In JavaScript, the console object provides methods for logging information to the console. It is available in all modern browsers and is primarily used for debugging. The most commonly used method is console.log(), but there are others, like console.warn(), console.error(), and console.info().

Examples using console.log()

We can use the console.log() method to print to the console. Here are some examples.

Example 1: Writing a string to the console

Let’s log a simple message to the console:

console.log("Welcome to Educative!");

In the code above, we’ve used the console.log() method to print a string “Welcome to Educative!” to the console.

Example 2: Writing values to the console

Let’s log some values of different types to the console:

console.log(3.14); // Logs a number
console.log("JavaScript"); // Logs a string
console.log(true); // Logs a boolean
console.log([1, 2, 3, 4]); // Logs an array
console.log({a: 1, b: 2}); // Logs an object

In the code above, we log the values of multiple types, including a number, string, boolean, array, and objects. We can see the given values being logged in the output.

Example 3: Writing multiple values to the console

We can log multiple values at once by separating them with commas. This helps print out various related variables in one go.

let name = "ABC";
let age = 25;
console.log("Name:", name, "Age:", age);

In the code above:

  • Lines 1–2: We define two variables: name to store the name and age to store the age.

  • Line 4: Using commas to separate the string and variables, we logged the name and age.

Example 4: Writing expression in the console.log() method

We can write expressions in the console.log() method. It calculates the output of the expression first and logs the answer to the console.

let a = 10;
let b = 5;
console.log("Sum of a and b is:", a + b);

In the code above:

  • Lines 1–2: We define variables a and b to store the numbers.

  • Line 4: We log the string “Sum of a and b is:” and use a comma to write the expression a + b. The expression output is calculated and logged in front of the string in the output. The output is as follows:

Sum of a and b is 15

Example 5: Logging objects and properties to the console

One of the most powerful features of console.log() is its ability to display complex data structures like arrays and objects. We can even access the object’s properties by expanding the object in the console.

let person = {
name: "Bob",
age: 30,
hobbies: ["reading", "coding", "hiking"]
};
console.log("person:", person);
console.log("person.hobbies:", person.hobbies);

In the code above:

  • Lines 1–5: We create an object named person with three properties: name to store the name, age to store the age of the person, and hobbies to store the array containing the person’s hobbies.

  • Line 7: We log the object to the console, where we can see the person object with all of its properties.

  • Line 8: We log the hobbies property of the person object to the console to see the array of hobbies.

Example 6: Formatting console output

console.log() allows for formatted output. We can use placeholders to format strings. Some of the most common placeholders are %s for strings, %d for numbers, and %c for applying CSS styling.

console.log("My name is %s and I am %d years old.", "John", 28);

We use %s and %d in the above code to show the provided comma-separated string and number.

Common use cases for console.log()

  • Debugging: One of the primary use cases of console.log() is debugging. By printing variable values or function outputs, we can track where things might go wrong in the code.

  • Tracking function calls: We can use console.log() to verify when a function is called and with what arguments. This ensures that the function behaves as expected.

  • Conditional logging: We can use console.log() to print messages only when certain conditions are met, making tracking specific behaviors in the code easier.

  • Performance monitoring: We can use console.log() to check how long a block of code takes to execute, helping us identify performance bottlenecks.

  • Inspecting DOM elements: In web development, we can use console.log() to inspect DOM elements and their properties when interacting with the page.

Best practices for using console.log()

While console.log() is a powerful tool, it’s essential to use it wisely, especially in larger projects. Here are a few best practices:

  • Remove unnecessary logs: After debugging, remove or comment out unnecessary logs to keep the console clean.

  • Use meaningful messages: Always use descriptive messages in the logs to make them easy to understand.

  • Be cautious in production: Avoid leaving logs in production code unless necessary. Excessive logging can clutter the console and affect performance.

Note: You can explore our JavaScript Catalog to learn everything from basics to advanced concepts!

Knowledge test

Let’s attempt a short quiz to assess our understanding.

1

What does the log() part in console.log() represent?

A)

A function to send requests

B)

A function to add numbers

C)

An object to store data

D)

A method to output a message to the console

Question 1 of 20 attempted

Conclusion

The console.log() method allows us to view the output of their functions, log data, and understand the behavior of the application in real time. Whether we’re tracking the execution of loops, checking variable states, or monitoring performance, console.log() gives us direct insights into how the code operates. While it is a simple method, its impact on debugging and troubleshooting can be profound. However, we should be mindful of using it in production environments to maintain performance and avoid cluttering the console with unnecessary logs.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to run JavaScript in the console

To run JavaScript in the console, follow the steps below:

  1. Open your browser’s “Developer” tools (usually accessible by pressing F12 or Ctrl + Shift + I).
  2. Navigate to the “Console” tab.
  3. Type any valid JavaScript code in the console and press Enter. For example, typing console.log('Hello, World!'); will display the message “Hello, World!” in the console.

How to use the console for JavaScript

The console in JavaScript provides a way to interact with the browser’s developer tools. It is commonly used for debugging purposes and can output messages, inspect DOM elements, or view runtime errors. We can:

  • Use console.log() to print values or objects.
  • Use console.warn() to display warnings.
  • Use console.error() to log errors.
  • Use console.info() to show general information.

By typing commands directly into the console, we can experiment with code in real-time or inspect how certain parts of the script behave during execution.

For a more detailed hands-on coverage of JavaScript console, have a look at What is the JavaScript console object and what are its methods?


How to console log input in JavaScript

To log user input in JavaScript, we can prompt the user for input using the prompt() function and then log the input using console.log(). Here’s a simple example:

var userInput = prompt("Enter your name:");
console.log("User entered: " + userInput);

In this example:

  • The prompt() function asks the user for their input.
  • The input is stored in the userInput variable.
  • Finally, console.log() outputs the user input to the console.

This method is useful for capturing and debugging user input during development.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved