The Wayback Machine - https://web.archive.org/web/20240920014719/https://www.geeksforgeeks.org/javascript-comma-operator/
Open In App

JavaScript Comma Operator

Last Updated : 29 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript Comma Operator mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand. It is used as a separator for multiple expressions at a place that requires a single expression. When a comma operator is placed in an expression, it executes each expression and returns the rightmost expression.

Syntax

Expression1, Expression2, Expression3, ...so on

In the above syntax, multiple expressions are separated using a comma operator. During execution, each expression will be executed from left to right and the rightmost expression will be returned.

Example 1: Below is an example of the Comma operator.

javascript
function Func1() {
    console.log('one');
    return 'one';
}
function Func2() {
    console.log('two');
    return 'two';
}
function Func3() {
    console.log('three');
    return 'three';
}

// Three expressions are
// given at one place
let x = (Func1(), Func2(), Func3());

console.log(x);

Output
one
two
three
three

Example 2: The most useful application of the comma operator is in loops. In loops, it is used to update multiple variables in the same expression.

javascript
for (let a = 0, b =5; a <= 5; a++, b--) {
    console.log(a, b);
}

Output
0 5
1 4
2 3
3 2
4 1
5 0

Example 3: Using the comma operator to initialize multiple variables in a single statement.

JavaScript
let a = 1, b = 2, c = 3;

console.log("Initial values:");
console.log("a:", a);
console.log("b:", b);
console.log("c:", c);

// Using comma operator to update multiple variables
(a *= 2), (b *= 3), (c *= 4);

console.log("Updated values:");
console.log("a:", a);
console.log("b:", b);
console.log("c:", c);

Output
Initial values:
a: 1
b: 2
c: 3
Updated values:
a: 2
b: 6
c: 12


We have a complete list of JavaScript Operators, to check those please go through the Javascript Operators Complete Reference article. 

Supported Browsers

  • Google Chrome
  • Firefox
  • Apple Safari
  • Opera

JavaScript Comma Operator – FAQs

What is the comma operator in JavaScript?

The comma operator allows multiple expressions to be evaluated in a single statement, returning the value of the last expression.

How does the comma operator work?

When the comma operator is used, each expression is evaluated from left to right, but only the result of the final expression is returned.

Where is the comma operator commonly used?

The comma operator is often used in for loops to include multiple expressions within the loop initialization or increment sections. It can also be used in variable assignments and other contexts where multiple operations need to be performed in sequence.

Can the comma operator be used in variable declarations?

Yes, the comma operator can be used to include multiple expressions in a single variable declaration statement, but only the last expression’s value will be assigned to the variable.

How does the comma operator compare to semicolons in JavaScript?

Semicolons separate statements, each of which is evaluated independently. The comma operator allows multiple expressions to be evaluated within a single statement, with only the last expression’s result being returned.

Can the comma operator be used in function arguments?

Yes, the comma operator can be used in function arguments to evaluate multiple expressions, but only the last expression’s value will be passed as the argument.



Previous Article
Next Article

Similar Reads

How to convert a 2D array to a comma-separated values (CSV) string in JavaScript ?
Given a 2D array, we have to convert it to a comma-separated values (CSV) string using JS. Input:[ [ "a" , "b"] , [ "c" ,"d" ] ]Output:"a,b c,d"Input:[ [ "1", "2"]["3", "4"]["5", "6"] ]Output:"1,23,45,6"To achieve this, we must know some array prototype functions which will be helpful in this regard: Join function: The Array.prototype.join( ) funct
4 min read
Convert comma separated string to array using JavaScript
In JavaScript, it's common to encounter comma-separated strings that need to be converted into arrays for further processing or manipulation. Whether you're parsing user input, handling data from an external source, or performing string operations, knowing how to convert a comma-separated string to an array is important. A comma-separated string ca
5 min read
Create a Comma Separated List from an Array in JavaScript
In this article, we will see how to convert an array into a comma-separated list using JavaScript. To do that, we are going to use a few of the most preferred methods. Methods to Create Comma Separated List from an Array: Table of Content Array join() methodArray toString() methodUsing Array literalsUsing Lodash _.join() methodUsing map() and join(
3 min read
Angular PrimeNG Form Chips Comma Separator Component
Angular PrimeNG is an open-source library that consists of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see Angular PrimeNG Form Chips Comma Separator Component. The Chips Component in PrimeNG is used to take input of many values in
3 min read
How to get comma separated KeyValue Pipe in Angular ?
The KeyValue Pipe is an Angular built-in feature that transforms objects or maps into an array of key-value pairs. We can use the last variable of *ngFor directive to achieve the desired result. We will compare that if the element is last then add a comma. In this article, we will learn how to get a comma-separated KeyValue Pipe in Angular. Steps f
3 min read
How to Convert CSV to JSON file having Comma Separated values in Node.js ?
A CSV is a comma-separated value file, identified by the .csv extension, is a format used for tabular data storage where values are separated by commas. This article presents a method to convert CSV data to JavaScript Object Notation (JSON) without any relaying on third-party npm packages. Unlike typical conversions, this approach handles scenarios
4 min read
How to use comma as list separator in AngularJS ?
In this article, we will use commas as a list separator in AngularJS applications. In AngularJS, we can use a list separator by simply placing the command between the items in the list. If we have an array of items that we need to display in the application, then we can use ng-repeat to iterate through this array and then display each item which is
4 min read
Why we should prefer square operator over the dot operator to access the value from the object ?
The square notation should be used as much as possible as compared to the dot notation to access the value from the object in JavaScript. Let's first understand how to obtain the value by using the square notation and dot notation from the object. Square notation: In the square notation the keyName that is passed is treated as a variable and search
3 min read
JavaScript Course Conditional Operator in JavaScript
JavaScript Conditional Operators allow us to perform different types of actions according to different conditions. We make use of the 'if' statement. if(expression){ do this; } The above argument named 'expression' is basically a condition that we pass into the 'if' and if it returns 'true' then the code block inside it will be executed otherwise n
3 min read
Left Shift Assignment (&lt;&lt;=) Operator in JavaScript
The Left Shift Assignment Operator is represented by "&lt;&lt;=". This operator moves the specified number of bits to the left and assigns that result to the variable. We can fill the vacated place by 0. The left shift operator treats the integer stored in the variable to the operator's left as a 32-bit binary number. This can also be explained as
2 min read
JavaScript ‘===’ vs ‘==’Comparison Operator
In Javascript(ES6), there are four ways to test equality which are listed below: Using '==' operatorUsing '===' operatorSameValueZero: used mainly in sets, maps and arrays.SameValue: used elsewhereNow, our main concern is getting to know the difference between the '==' and '===' operators that the javascript provides, though they look similar, they
3 min read
Arrow operator in ES6 of JavaScript
ES6 has come with various advantages and one of them is the arrow operator. It has reduced the function defining code size so it is one of the trending questions asked in the interview. Let us have a deeper dive into the arrow operator's functioning. Syntax: In ES5 a function is defined by the following syntax: function functionName(arg1, arg2….) {
4 min read
The 'new' operator in Javascript for Error Handling
In this article, we will see new operator usage during error throwing as well as handling the error() method in JavaScript using theoretical as well as coding examples. JavaScript new operator: The new operator is actually a special operator that is used along with the error() method which is the method for the error class used to instantiate any s
3 min read
What is the !! (not not) operator in JavaScript?
The !!(not not) is the repetition of the unary logical operator not(!) twice. The double negation(!!) operator calculates the truth value of a value. This operator returns a boolean value, which depends on the truthiness of the given expression. In general, logical not(!) determines the "truth" of what a value is not: The truth is that false is not
2 min read
How to get negative result using modulo operator in JavaScript ?
The %(modulo) operator in JavaScript gives the remainder obtained by dividing two numbers. There is a difference between the %(modulo) and the remainder operator. When remainder or %(modulo) is calculated on positive numbers then both behave similarly but when negative numbers are used then both behave differently. The JavaScript %(modulo) behaves
4 min read
What is JavaScript &gt;&gt;&gt; Operator and how to use it ?
The JavaScript &gt;&gt;&gt; represents the zero-fill right shift operator. It is also called the unsigned right-bit shift operator. It comes under the category of Bitwise operators. Bitwise operators treat operands as 32-bit integer numbers and operate on their binary representation. Zero-fill right shift (&gt;&gt;&gt;) operator: It is a binary ope
3 min read
What does +_ operator mean in JavaScript ?
Unary Operator: A unary operation contain only one operand. Here, the '+' unary plus operator converts its operand to Number type. While it also acts as an arithmetic operator with two operands which returns an addition result on calculation. JavaScript Identifiers: Javascript Identifiers are used to name variables (and keywords, functions, and lab
2 min read
JavaScript Unsigned Right Shift Assignment Operator
In JavaScript "&gt;&gt;&gt;=" is known as the unsigned right shift assignment bitwise operator. This operator is used to move a particular amount of bits to the right and returns a number that is assigned to a variable. Syntax: a &gt;&gt;&gt;= b Meaning: a = a &gt;&gt;&gt; b Return value: It returns the number after shifting of bits. Example 1: Thi
1 min read
JavaScript SyntaxError - Missing name after . operator
This JavaScript exception missing name after . operator occurs if the dot operator (.) is used in the wrong manner for property access. Message: SyntaxError: missing name after . operator Error Type: SyntaxError Cause of Error: The dot operator (.) is used to access the property. Users will have to provide the name of the properties to access. Some
1 min read
JavaScript SyntaxError - Applying the 'delete' operator to an unqualified name is deprecated
This JavaScript exception applying the 'delete' operator to an unqualified name is deprecated works in strict mode and it occurs if variables are tried to be deleted with the delete operator. Message: SyntaxError: Calling delete on expression not allowed in strict mode (Edge) SyntaxError: applying the 'delete' operator to an unqualified name is dep
1 min read
JavaScript TypeError - Cannot use 'in' operator to search for 'X' in 'Y'
This JavaScript exception Cannot use 'in' operator to search for 'X' in 'Y' occurs if in operator is used to search in strings, numbers, or other primitive types. It can not be used other than type-checking. Message: TypeError: Invalid operand to 'in' (Edge) TypeError: right-hand side of 'in' must be an object, got 'x' (Firefox) TypeError: cannot u
1 min read
JavaScript Remainder(%) Operator
The remainder operator in JavaScript is used to get the remaining value when an operand is divided by another operand. In some languages, % is considered modulo. Modulo and Remainder work differently when the sign of both operands is different. In JavaScript remainder takes the sign of the dividend and to get modulo ((a % n) + n) % n should be used
2 min read
Nullish Coalescing Assignment (??=) Operator in JavaScript
This is a new operator introduced by javascript. This operator is represented by x ??= y and it is called Logical nullish assignment operator. Only if the value of x is nullish then the value of y will be assigned to x that means if the value of x is null or undefined then the value of y will be assigned to x. Let's discuss how this logical nullish
2 min read
JavaScript Logical AND assignment (&amp;&amp;=) Operator
This operator is represented by x &amp;&amp;= y, and it is called the logical AND assignment operator. It assigns the value of y into x only if x is a truthy value. We use this operator x &amp;&amp;= y like this. Now break this expression into two parts, x &amp;&amp; (x = y). If the value of x is true, then the statement (x = y) executes, and the v
2 min read
JavaScript Logical OR assignment (||=) Operator
This operator is represented by x ||= y and it is called a logical OR assignment operator. If the value of x is falsy then the value of y will be assigned to x. When we divide it into two parts it becomes x || ( x = y ). It checks if x is true or false, if the value of x is falsy then it runs the ( x = y ) block and the value of y gets stored into
2 min read
JavaScript Arithmetic Unary Plus(+) Operator
The Unary plus(+) operation is a single operand operator (which means it worked with only a single operand preceding or succeeding to it), which is used to convert its operand to a number, if it isn't already a number. Syntax: +Operand Below examples illustrate the Unary plus(+) Operator in JavaScript: Example 1:This example shows the use of the Ja
1 min read
JavaScript Arithmetic Unary Negation(-) Operator
The Unary negation(-) operation is a single operand operator (which means it worked with only a single operand preceding or succeeding to it), which is used to convert its operand to a negative number, if it isn't already a negative number. Syntax: -Operand Example 1: This example shows the use of JavaScript Unary negation(-) Operator. C/C++ Code
1 min read
JavaScript Remainder Assignment(%=) Operator
JavaScript remainder assignment operator (%=) assigns the remainder to the variable after dividing a variable by the value of the right operand. Syntax: Operator: x %= y Meaning: x = x % y Below example illustrate the Remainder assignment(%=) Operator in JavaScript: Example 1: The following example demonstrates if the given number is divisible by 4
1 min read
Strict Equality(===) Comparison Operator in JavaScript
JavaScript Strict Equality Operator is used to compare two operands and return true if both the value and type of operands are the same. Since type conversion is not done, so even if the value stored in operands is the same but their type is different the operation will return false. Syntax: a===b Example 1: In this example, we will compare the val
2 min read
Multiplication Assignment(*=) Operator in JavaScript
Multiplication Assignment Operator(*=) in JavaScript is used to multiply two operands and assign the result to the right operand. Syntax: variable1 *= variable2 // variable1 = variable1 * variable2 Example 1: In this example, we multiply two numerical values using the Multiplication Assignment Operator(*=) and assign the result variable in javascri
1 min read