The description of comma operator says
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression
And the syntax and parameters also says that its operands should be expressions.
Syntax
expr1, expr2, expr3…
Parameters
expr1
,expr2
,expr3
…
Any expressions.
I want to know that why the following code doesnot throw error while it have a declaration let x = 3
let x = 3, y = 5 console.log(x,y)
If you put declaration in console.log()
it throws error it means its not expression.
console.log(let x = 3,y=3)
Advertisement
Answer
It’s only parsed as the comma operator when between expressions, not statements. let x = 3
is not an expression; it does not evaluate to any value. Trying to parse it as an expression does not work:
const result = let x = 3; console.log(result);
The syntax let <variableName> = <expression>, <variableName2> = <expression2>
is not invoking the comma operator – that syntax, when used around let
, const
, and var
, simply initializes multiple variables at once, and said syntax simply happens to use commas, despite the fact that they’re not interpreted as the comma operator.
In contrast, with
let x = 3, y = 5 console.log(x,y)
You’re not invoking the comma operator here, either: you have a parameter list. To invoke the comma operator, you also need to be not immediately inside a parameter list, eg:
let x = 3, y = 5 console.log((x,y))
or
let x = 3, y = 5 const someVar = (x,y); console.log(someVar);