I have a question that has arisen using the JavaScript throw keyword .
According to the documentation the syntax is:
throw expression;
Now, I've seen several examples using throw as if it were a function call, i.e. the expression in parentheses:
throw(new Error('Esto es un error'))
Furthermore, if we pass more than one argument to it, it will take the last argument:
throw(1, 2, 3, new Error('Esto es un error'), 'El último')
This behavior seems to be undocumented, the question would be, why doesn't it throw some syntax error?
If the syntax is correct, what's the point of being able to pass it so many arguments?
If I'm totally wrong, what am I missing here?
Throw is not a function, it is a statement so when you do this
you are executing the throw statement that is accompanied by an expression and not a list of parameters therefore the first level parentheses are unnecessary and do not indicate the execution of a function but rather serve as a grouping operator here , therefore you can omit them.
don't get confused with the syntax of a function, that to execute it you must use the parentheses and send a list of parameters
The parameters you send to the function are expressions
here the first level of parentheses executes the function [hello], the second level of parentheses serve as a grouping operator that resolves to the same value 'Pepe'.
Javascript functions can receive N number of parameters, if when executing you send more parameters than necessary then the function will take the first ones until it matches the number of parameters it receives and discards the excess.
but this is different than a comma separated list of expressions like for example
The comma can be used to separate expressions that you write on a single line so it is equivalent to this.
The throw clause can receive an Error object or not, you can send any value to throw like strings, numbers or other objects.
So in your example this line
It is equivalent to
Since it is an expression and not a list of parameters, this expression resolves to the last value, in your case it is the string 'Last'.
and finally the semicolon delimits the statement therefore these are not equivalent