In this chapter, we will learn about the console.log()
method in JavaScript. This method is one of the most commonly used tools for debugging and displaying information in the browser’s console. We will cover:
- What is
console.log()
? - Basic Usage
- Formatting Output
- Logging Multiple Values
- Logging Objects and Arrays
- Console Methods
- Simple Programs using
console.log()
What is console.log()?
The console.log()
method outputs a message to the web console. It is often used for testing purposes to check the values of variables and the flow of code.
Basic Usage
The console.log()
method takes one or more parameters, which can be of any type, and prints them to the console.
Syntax
console.log(message);
Example
console.log("Hello, World!");
Output:
Hello, World!
Formatting Output
You can format the output of console.log()
using format specifiers, similar to printf
in C.
Example
let name = "Amit";
let age = 25;
console.log("Name: %s, Age: %d", name, age);
Output:
Name: Amit, Age: 25
Logging Multiple Values
You can pass multiple values to console.log()
to print them in a single line.
Example
let firstName = "Amit";
let lastName = "Kumar";
let age = 25;
console.log(firstName, lastName, age);
Output:
Amit Kumar 25
Logging Objects and Arrays
The console.log()
method can also be used to log objects and arrays, providing a clear and readable output.
Example
let person = {
firstName: "Amit",
lastName: "Kumar",
age: 25
};
let numbers = [1, 2, 3, 4, 5];
console.log(person);
console.log(numbers);
Output:
{ firstName: 'Amit', lastName: 'Kumar', age: 25 } [ 1, 2, 3, 4, 5 ]
Simple Programs using console.log()
Program 1: Debugging a Function
function add(a, b) {
console.log("a:", a);
console.log("b:", b);
return a + b;
}
let result = add(5, 10);
console.log("Result:", result);
Output:
a: 5
b: 10
Result: 15
Program 2: Looping through an Array
let numbers = [10, 20, 30, 40, 50];
for (let i = 0; i < numbers.length; i++) {
console.log("Index:", i, "Value:", numbers[i]);
}
Output:
Index: 0 Value: 10
Index: 1 Value: 20
Index: 2 Value: 30
Index: 3 Value: 40
Index: 4 Value: 50
Conclusion
In this chapter, you learned about the console.log()
the method in JavaScript, including its basic usage, formatting output, logging multiple values, and logging objects and arrays. Understanding how to effectively use console.log()
method is essential for debugging and testing your JavaScript code.