Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional ternary operator is giving error: Expected an assignment or function call and instead saw an expression when setting a variable

I would like to set a param for knowing what uri to use when a certain port is called.

Here is my code:

  var portConfig = '443';
    (portConfig === '443') ? uri = 'wss://' : uri = 'http://';
    console.log(uri);
    var Ip = uri + "hereis.myurl.com";
    var port = portConfig;
    console.log(Ip);

I am getting the following error:

Expected an assignment or function call and instead saw an expression

I have even set the uri's to be inside of a function testA testB but the same error occurs. I have read up on the issue and it just seems like an erroneous error. Should I use the if statement instead -- which works fine?

like image 812
Christian Matthew Avatar asked May 31 '26 18:05

Christian Matthew


2 Answers

The correct way per documentation is:

uri = (portConfig === '443') ? 'wss://' : 'http://';

It does indeed expect the assignment, not the expression.

In fact, the way you use could be eaten and parsed without the errors by the browser, since an assignment returns the assigned value. But it's not the recommended way, since the ternary operators were designed to return the value (and they do it always, even if you don't use the value afterwards), unlike if() conditions, and it's considered not wise to use it like you use if().

like image 126
nicael Avatar answered Jun 03 '26 07:06

nicael


This is how you should write it

uri =  (portConfig === '443') ? 'wss://' : 'http://';
like image 45
Alon Eitan Avatar answered Jun 03 '26 07:06

Alon Eitan