JavaScript console.log() Method
In JavaScript, console.log() method is a built-in JavaScript function that outputs messages to the console, which is a special area in web browsers or runtime environments for developers to view information about their code.
It is primarily used for:
- Debugging code
- Inspecting variables
- Tracking the flow of execution
- Logging errors or warnings
Syntax:
console.log("");- message: The value, variable, or expression you want to print.
- Message can be a string, number, object, array, or any valid JavaScript expression.
- It returns the value of the parameter given.
Using Console.log()
The console.log() method is one of the most widely used debugging tools in JavaScript. It prints messages, variables, and expressions to the console, helping developers understand how their code is running.
console.log("Hello Geeks")
Output
Hello Geeks
We can even print an array or an object on the console using log() method
Logging a Object and Array
The console.log() method can log not only strings and numbers but also complex data types like objects and arrays. This makes it especially useful when debugging applications.
- Logging an Object: When you log an object directly, the console shows it in an expandable format, so you can explore its properties:
let user = {
name: "Alice",
age: 25,
city: "New York"
};
console.log(user);
Output
{ name: "Alice", age: 25, city: "New York" }- Logging an Array: Arrays can also be logged directly. The console shows them as a list of values with their index positions:
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits);
Output
["Apple", "Banana", "Cherry"]Which of the following is NOT a typical use of console.log()?
-
A
Debugging code
-
B
Inspecting variables
-
C
Logging execution flow
-
D
Compiling JavaScript into machine code
console.log() is only for outputting messages to the console. It does not compile JavaScript or affect execution behavior.
What does console.log() return?
-
A
Always
undefined -
B
The value passed to it
-
C
A Promise that resolves after printing
-
D
A boolean indicating success
console.log() returns the same value you pass as the argument, although the console itself prints the value separately.
When logging an object using console.log(user), how does the console typically display it?
-
A
As a JSON string automatically
-
B
As an unreadable memory address
-
C
In an expandable format showing key–value pairs
-
D
Only as
[object Object]
Modern JavaScript consoles display objects in expandable tree format, allowing inspection of properties.
Consider the code:
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits);
How will the console display the output?
-
A
{0: "Apple", 1: "Banana", 2: "Cherry"} -
B
"Apple,Banana,Cherry" -
C
A list showing index positions and values
-
D
It throws an error
Consoles show arrays as indexed lists, such as:
["Apple", "Banana", "Cherry"]