×

JavaScript Console log Multiple variables

What does console.log() do in JavaScript?

The console.log() is a function in JavaScript language. It is used to:

  • Print any message in the console which is visible to the user
  • Print the values of variables defined

Advantages of console.log()

  • Multiple browsers support this function, for example, Google Chrome, Safari, Microsoft Edge/Internet Explorer, Firefox, Opera etc.
  • This function is primarily used for testing purposes.

NOTE: When F12 key is pressed on the website, the console view is visible.

Syntax:

console.log(“message”)

Here, “message” is any string.

Or

console.log(var)

Here, “var” denotes any variable which has a value stored in it.

The function can take any array, object or value as a Parameter. It then returns the value according to the parameter.

Example:

<script>
var name = "Javatpoint";
console.log(name);
</script>

Output:

Javatpoint

Example:

<script>
console.log(“Hello”);
</script>

Output:

Hello

Multiple variables in console.log()

We know, that when we pass a single variable to the console.log(), the following output is generated:

Example:

<script>
    let x = 2;
    console.log(x);
</script>

Output:

2

But suppose, if we have multiple variables, instead of writing the function of console.log() multiple times, we can include all the variables in a single line.

Example:

<script>
    let x = 2;
    let y = 3;
    let z = 6;
    console.log(x,y,z);
</script>

Output:

2 3 6

Tips to use while using multiple variables in console.log()

1. Referring the multiple variables by name

When multiple variables are passed in console.log(), it sometimes gets difficult to recognize which variable corresponds to a log in the console.

Example:

<script>
    		let x = 2;
    		let y = 3;
    		let z = 6;
   	 	console.log(x,y,z);
</script>

Output:

2 3 6

Here, it is difficult to identify what values corresponds to which variable.

To overcome that, use curly braces { } along with the variable to make an association between the variable and value.

Example:

<script>
    		let x = 2;
    		let y = 3;
    		let z = 6;
    		console.log( {x, y, z} );
</script>

Output:

{x: 2, y: 3, z: 6}

Similarly, curly braces can be used with the objects as well.

Example:

<script>
   		let obj1 = {
  		name: 'Javatpoint',
 		 age: 18
                       }
                       console.log(obj1)
                       console.log({obj1})
</script>

Output:

{name: "Javatpoint", age: 18}	
{obj1: {…}}

2. Formatting

When we want to print a message containing multiple variables along with a message, we can format console.log() accordingly by:

  • Using specifiers like %s, %i, %f etc.

Example:

<script>
   let user = 'Rahul';
   let age = 25;
   console.log('%s is %i years old', user, age);
  </script>

Output:

Rahul is 25 years old

Here, we are formatting a message containing a string and an integer, therefore %s is used for “user” and %i is used for “age”.

Following is a list of other specifiers, that can be used as well:

SpecifierDescription
%sUsed for string elements
%d or %iUsed for integer elements
%fUsed for float type of elements
%oUsed for optimally useful formatting in elements
%OUsed for generic JavaScript object formatting in elements
%cUsed to add additional CSS formatting
  • Concatenating the variables

When we want to print two or more strings together,”+” operator can be used as well to combine them together.

Example:

<script>
let x = 'Java';
let y = 't';
let z = 'point';
let year = 2021;
console.log(x+y+z);
console.log(x+y+z+year);
</script>

Output:

Javatpoint
Javatpoint2021

NOTE: If all the variables contain integers, then “+” operator won’t concatenate the variables, it will simply add the integers and display the sum.

3. Adding CSS styles

By using the %c specifier in the console.log(), you add corresponding CSS styles along with specifier. Various browsers support the CSS formatting.

Example:

If we want to change the font size, font style and underline the text.

<script>
console.log('%cFormatted message', 'font-size: 25px; font-style: italic; text-decoration: underline;');
</script>

Output:

JavaScript Console Log Multiple Variables

Here, The specifier %c applies the CSS styles , 'font-size: 25px; font-style: italic; text-decoration: underline;'.

4. Adding interactive logs along with the messages

The %o specifier (Used for optimally useful formatting in elements) can insert objects, DOM elements, and normal text into a textual message.

Example:

<script>
const obj = {
name: 'Rahul',
	surname: 'Gupta'
};
console.log('Hello, new user %o', obj);
</script>

Output:

Hello, new user {name: "Rahul", surname: "Gupta"}

Related Topics

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

JavaScript p5.js

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

4 minutes read.

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to...

4 minutes read.

JavaScript dropdown onchange

What is onchange event? It is an event in JavaScript used to make the web pages dynamic. The onchange event gets triggered whenever the value of an event changes. It usually...

3 minutes read.

Minify JavaScript

What do you mean by the term ‘Minification’? The technique of minification reduces the amount of code and markup in your websites and scripting files. It's one of the most used...

4 minutes read.

JavaScript redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.Parameters can...

4 minutes read.

JavaScript setInterval()

On the Window and Worker interfaces, the setInterval() method calls a function or executes a snippet with a specified time delay between each call. This function provides an interval ID that...

4 minutes read.

Javascript Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes read.

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on...

3 minutes read.

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

1 minute read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.

Javascript Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

2 minutes read.

Javascript Object

An object is an entity having state and behavior. JavaScript is an object oriented scripting language. JavaScript is template based not class based but we can create object directly. Syntax to...

2 minutes read.

Javascript input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

Javascript Date

In JavaScript Date Object is data type build into the JavaScript language. Data object are created with the new Date(). JavaScript Date instance that represents a single moment in time. JavaScript...

2 minutes read.

Javascript Event

Events are things that happen, usually user action, that are associated with an object. All object have properties and methods. Some objects also have events. The event handler is a command that is...

1 minute read.

JavaScript Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 minutes read.