JavaScript console log() Method

JavaScript console.log() method is “used to write (log) a message to the console”. The console.log() method is helpful in testing.

To enable more advanced formatting, it can also accept format specifiers, such as %s for strings, %d or %i for integers, and %f for floating-point numbers.

Syntax

console.log(message)

Parameters

“message”: The parameter is required, which is the message to write to the console.

Return value

None.

Example 1: How to Use console.log() Method

console.log("Homer, Simpson!");

const fname = "Bart Simpson";
const age = 9;

console.log('My name is', fname, 'and I am', age, 'years old.');

console.log('My name is %s and I am %d years old.', fname, age);

Output

Homer, Simpson!
My name is Bart Simpson and I am 9 years old.
My name is Bart Simpson and I am 9 years old.

Example 2: Passing a character to the console.log() method

If you pass a char to the function console.log(), the function will display it.

let char = "21";

console.log(char);

Output

21

Example 3: Passing a function to the console.log() method

If you pass a function as an argument, the console.log() method will display the value of the passed function.

function meth() {
  return (21 * 19);
}

console.log(meth());

Output

399

Example 4: Passing a number to the console.log() method

If you pass the number to the console.log() method,  it will display it with a provided message.

let num = 21;

console.log("The value of num is: ", num);

Output

The value of num is: 21

Browser compatibility

All the browsers support it.

That’s it.

Leave a Comment