In JavaScript, the console.log() method displays messages or variables in the browser's console.
Here's a quick example of console.log(). You can read the rest of the tutorial for more details.
Example
let message = "Hello, JavaScript!";
console.log(message);
// Output: Hello, JavaScript!
When we run the above code, Hello, JavaScript! is printed on the console.
Syntax of JavaScript console.log()
console.log(message);
Here, message is a value or a variable whose value is to be printed to the console.
Example 1: JavaScript console.log() Method
console.log("Good Morning!");
console.log(2000);
Output
Good Morning! 2000
Here,
console.log("Good Morning!")prints the string"Good Morning!"to the console.console.log(2000)prints the number 2000 to the console.
Example 2: Print Values Stored in Variables
We can also use console.log() to display the values stored in variables. For example,
// store value in greet variable
const greet = "Hello";
// print the value of greet variable
console.log(greet);
Output
Hello
In this example, we have used console.log() to print the value of the greet variable, which is set to the string "Hello".
More on JavaScript console.log()
In JavaScript, you can combine strings and variables in console.log() using the following methods:
1. Using Substitution Strings
let count = 5;
console.log("There are %d items in your basket.", count);
// Output: There are 5 items in your basket.
In this example, we used the substitution string %d in console.log() to insert the value of the count variable into the printed message.
Here, %d is a placeholder for a decimal or integer number.
2. Using Template Literals
We enclose a message inside two backticks ` ` to utilize template literals. For example,
let count = 5;
// use template literals
let message = `There are ${count} items in your basket.`;
console.log(message);
// Output: There are 5 items in your basket.
Here, we inserted the value of the count variable inside the message using the code ${count}.
Also Read: