Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean when variable value in round brackets?

Tags:

javascript

What does it mean when variable value in round brackets in js? For example,

let a = (1,2,3);

What does it mean and why console.log(a) output is 3?

What is usage of comma operator in round brackets in variable initialization?

like image 485
Kate Avatar asked Jan 19 '26 22:01

Kate


1 Answers

The parentheses are needed for grouping. In a let statement, commas are normally used to separate multiple variables that are being declared, e.g.

let a = 1, b = 2, c;

which is short for

let a = 1;
let b = 2;
let c;

If you write

let a = 1, 2, 3;

you'll get a syntax error, because after the comma it expects another variable declaration; it's equivalent to:

let a = 1;
let 2;
let 3;

The second and third declarations are clearly wrong, as 2 and 3 are not variable names.

The parentheses indicate that the whole expression 1, 2, 3 is being used to initialize one variable.

The expression 1, 2, 3 uses the Comma operator, which executes each of its subexpressions and returns the last one as its value. It's pretty useless when the subexpressions are all constants, so I assume your code was just a simplified example. Because the way it's written, it's really just equivalent to:

let a = 3;
like image 200
Barmar Avatar answered Jan 22 '26 12:01

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!