Open In App

How to use console.log() for multiple variables

Last Updated : 27 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, console.log() is a method that is used to print values or output any message to the console of the browser. To view the console of the browser we press F12 keyboard key shortcut in the browser. This method is mainly used by developers for testing or debugging purpose. 

In this article we will discuss various methods to display multiple variables on the console.

Syntax:

console.log(val)

Parameters: It can take multiple parameters which can be a variable, string or a combination of both.

Return value: It prints the message passed as a parameter on the console.

Method 1: Passing variables separated by commas

  • Declare the variables and pass random values
  • Call the console.log method and pass variable separated by commas

Example: This example implements the above method.

Javascript




let var1 = 5;
let var2 = "Hello GEEK";
let var3 = true;
  
console.log(var1, var2, var3);


Output

5 Hello GEEK true

Using the above method the readability decreases as we do not know which value belongs to which variable. So we use the curly braces approach to solve this problem

Method 2: Passing variables separated by commas in curly braces

  • Declare the variables and pass random values
  • Call the console.log method and pass variable separated by commas
  • Enclose the variable values in curly braces

Javascript




let var1 = 5;
let var2 = "Hello GEEK";
let var3 = true;
  
console.log({var1, var2, var3});


Output

{ var1: 5, var2: 'Hello GEEK', var3: true }

If we want to print a variable with message we can use specifiers like %s, %f,%o in the console.log methods parmaeter.

Method 3: Using specifiers

  • Declare the variables and pass random values
  • Call the console.log method and pass the message as a string
  • Add specifiers at the place where you want the variable
  • add a comma after message and write the variable names

Javascript




let var1 = "DSA";
let var2 = "Web Development";
  
console.log("Use GeeksforGeeks to learn %s and %s", var1, var2);


Output

Use GeeksforGeeks to learn DSA and Web Development

Method 4: By using template literals

  • Declare the variables and pass random values
  • Call the console.log method and pass the message as a string in backticks
  • Add ${} and variable name inside it

Javascript




let var1 = "DSA";
let var2 = "Web Development";
  
console.log(`Use GeeksforGeeks to learn ${var1} and ${var2}`);


Output

Use GeeksforGeeks to learn DSA and Web Development



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads