How to Use Console.log() for printing in JavaScript

How to Use Console.log() for printing in JavaScript

Understanding console.log() in JavaScript

console.log() is a built-in function in JavaScript that allows us to print messages or values to the browser's console. This is particularly useful for debugging and testing code. Let’s explore its usage with examples and explanations.


What is console.log()?

Whenever we want to print something on the console, we use the console.log() function.

In simple terms:
It helps us display messages in the console (a technical way of saying "log a message").


Syntax

javascriptCopy codeconsole.log("Hello!");

Correct Usage vs. Incorrect Usage

Correct Example

Incorrect Example


console.log() with Multiple Data Types

console.log() can handle various types of data, including text, numbers, and even expressions.

multiple data types

  • console.log ( “Hello world from hello college”);

  • console.log ( “ hii college”);

  • console.log ( 1234 );

  • console.log ( 2 + 2 );

  • console.log ( “hello ” , “ college” , 123 )

Examples

  1. Printing a String:

  2. Printing Numbers:

     console.log(1234);
    
  3. Evaluating Expressions:

     console.log(2 + 2); // This prints 4, not "2 + 2".
    
  4. Displaying Multiple Values Together:

     console.log(" hello ", "College", 123); // Prints: Apna College 123
    

Detailed Explanation

1. String Output

console.log("Hello world from Apna College");

Code Output:
"Hello world from Apna College"


2. Number Output

javascriptCopy codeconsole.log(1234);

Code Output:
1234

Correct Output:

Incorrect Output:


3. Expression Evaluation

console.log(2 + 2);

Code Output:
4


4. Multiple Values Display

console.log("Apna", "College", 123);

Code Output:
Apna College 123


The Role of console.log() in Browsers

The primary purpose of console.log() is to connect your JavaScript file with the browser. It serves as a bridge to view output messages and debug code directly in the browser's console.