what's the difference between comma operator and comma separator? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 1

what's the difference between comma operator and comma separator?

var x =(1,2,3) and var x = 1,2,3

24th Oct 2022, 5:13 PM
bizzzzzzzo
6 Respostas
+ 3
Personally, I take the comma as a punctuation mark and nothing more. The compiler reads the code from left to right, from top to bottom in line. That is, it evaluates all expressions to the end of the string and only then performs a simultaneous operation. So the comma is the separator of expressions of one line. A semicolon ends the string. So: In the first case, you declare a variable and assign an expression to it. The compiler sees the opening brace and evaluates the given expression until it encounters a closing brace. It is the closing bracket that tells the compiler to complete the evaluation and assign the final result to the variable, and not the comma šŸ¤” In the second example, you declare a variable and assign it a certain number after which the compiler sees a comma and the next number for which there is neither a declared variable nor any operation on it, so it panics, because it expects to meet either a dot or a semicolon , or a new expression. Debug: var x; x = 1,2,3; //out: 1
24th Oct 2022, 10:11 PM
Solo
Solo - avatar
+ 5
Ok now I actually learned something interesting. The comma operator (,) evaluates each of its operands (from left to right) and returns the value of the last operand. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
24th Oct 2022, 6:15 PM
Tibor Santa
Tibor Santa - avatar
+ 1
Neither of your examples are really meaningful in JavaScript. In the first case, the number 1 and 2 are discarded and X will take the value of 3. The second case does not even run because it is a syntax error. I am not really sure why the first example even works, but it looks ugly. The parentheses have many different meanings, I think in this case it is the grouping operator. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping But for it to contain values separated by commas is rather meaningless. If you want to declare an array, you need to use curly braces {}
24th Oct 2022, 6:13 PM
Tibor Santa
Tibor Santa - avatar
+ 1
So if i wonna retake the answer after reading your answers it will be: like we use comma in this code var x =2 , y= 5, z= 10; we used to do this. So the compiler take the argument one after the other. Now, it's understood very well. Thank you all.
25th Oct 2022, 2:36 AM
bizzzzzzzo
+ 1
Another way to declare variables with values: let [a,b,c]=[1,2,3];
25th Oct 2022, 4:42 AM
Solo
Solo - avatar
0
yes this is destruction mode where in assign each value to right to each variable to the left
26th Oct 2022, 7:20 PM
bizzzzzzzo